我有一个文本文件“Test 2.txt”,格式如下:
string1
string2
string3
string4
string5
string6
string7
string8
string9
...and so on...
我想将其转换为文本文件“Test.txt”,格式如下:
string1,string2,string3
string4,string5,string6
string7,string8,string9
...and so on...
目前我的代码如下:
string line;
string DatabaseFullPath = @"C:\Test2.xsr";
using (var file = new StreamReader(DatabaseFullPath, Encoding.UTF8))
{
int count = File.ReadLines(DatabaseFullPath).Count();
while ((line = file.ReadLine()) != null)
{
count++;
if (count % 3 == 0)
{
using (StreamWriter writetext = new StreamWriter(@"D:\Test.txt"))
{
writetext.WriteLine(line + '\n');
}
}
else
{
using (StreamWriter writetext = new StreamWriter(@"D:\Test.txt"))
{
writetext.Write(line + ',');
}
}
}
}
似乎StreamWriter只是用另一个字符串“line”覆盖每个字符串“line”,但我不确定。
答案 0 :(得分:1)
string DatabaseFullPath = @"C:\Test2.xsr";
using (var file = new StreamReader(DatabaseFullPath, Encoding.UTF8)) {
using (StreamWriter writetext = new StreamWriter(@"D:\Test.txt")) {
int count = 0;
string line;
while ((line = file.ReadLine()) != null) {
if (++count % 3 == 0)
writetext.WriteLine(line);
else
writetext.Write(line + ',');
}
}
}