每个文件夹都有一长串文本文件(大约80-100个文件)。我必须将每4个文本文件合并为一个文本文件。每个文本文件都是一个单独的SQL Insert命令,因此4个文本文件中第一个文本文件的第一行必须保留在输出文件中(Insert INTO数据库(value1,value2,value3)VALUES),其余3个文件应该跳过第一行,只保留值。
我遇到的问题是,当组合4个文件中的最后一个时,最后一个文件只将最后一个的大约一半复制到新的组合文件中。
即使我尝试将3个文件或2个文件合并为一个文件。它仍然只复制最后一个文件的大约一半。
这是我的密码。
fourCount
指示第四个文本文件何时已经被组合。
string[] array2 = sqlInsertList.ToArray();
StreamWriter outfile3 = new StreamWriter(folderPath.Text + "\" + count + ".txt");
count++;
foreach (string dirFileName in array2)
{
StreamReader readFile = new StreamReader(dirFileName);
string readFromFile = readFile.ReadLine();
if(fourCount == 1)
{
outfile3 = new StreamWriter(folderPath.Text + "\" + count + ".txt");
outfile3.WriteLine(readFromFile);
}
while(!readFile.EndOfStream)
{
readFromFile = readFile.ReadLine();
outfile3.WriteLine(readFromFile);
}
count++;
if(fourCount == 4)
{
outfile3.WriteLine(";");
fourCount = 1;
}
else
{
fourCount++;
}
}
您没有关闭,因此没有刷新输出文件。
更改为:
using(StreamWriter outfile3 = new StreamWriter(...))
{
count++;
foreach (string dirFileName in array2)
{
if(fourCount == 1)
{
outfile3.Close(); // add this
outfile3 = new StreamWriter(folderPath.Text + "\" + count + ".txt");
outfile3.WriteLine(readFromFile);
}
...
}
}
您可以将auto-Flash设置为true属性或使用Flush方法,
然而,打开流是没有好处的,所以如果可能的话,当您知道不需要它时,请关闭它。