我的文本文件包含不同的字符串,每个字符串都在一个单独的行中,如
1
2
3
我需要一个C#代码来获取输入和输出文件,读取文本输入并用逗号替换断行,这样输出文件应该包含 运行代码后的1,2,3
答案 0 :(得分:3)
写一些像这样的代码
for each line in the file
add line to a stringbuilder
add, to stringbuilder
write stringbuilder.ToString() to new text file
答案 1 :(得分:0)
string line;
var str=new List<string>();
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
str.Add(line);
}
file.Close();
return string.Join(",",str);
看这里:
https://msdn.microsoft.com/en-CA/library/aa287535(v=vs.71).aspx
答案 2 :(得分:0)
借用这个答案:C#: How to read lines from text file and output them split by comma in another text file
using (TextFieldParser parser = new TextFieldParser(@"c:\temp\test.txt"))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters("\n");
string csvData = "";
while (!parser.EndOfData)
{
//Processing row
string[] fields = parser.ReadFields();
foreach (string field in fields)
{
csvString += field + ",";
}
csvString += "\n";
}
}
其中csvString是你的答案
答案 3 :(得分:-1)
如果文件相对较小,那么可能是一个单行解决方案?
File.WriteAllText (@"c:\path\file2.txt", String.Join (",", File.ReadAllLines(@"c:\path\file1.txt")));