我正在尝试将一行文本写入75次并将数字增加1,直到达到75的条件。从2开始是有原因的。 这是代码
class WriteTextFile
{
static void Main()
{
string path = "C:\\Users\\Writefile\\test.txt";
string line;
int i = 2;
while (i <= 75 )
{
line = "Error_Flag = 'FOR_IMPORT' and location_type = 'Home' and batch_num = " + i + "\n";
System.IO.File.WriteAllText(@path, line);
i++;
}
}
}
这样,它最后只写了一行75。我希望它用相同的东西写出所有74行,每次只有这个数字上升。谢谢。
答案 0 :(得分:6)
System.IO.File.WriteAllText
每次都会覆盖文件的内容。
你应该做的是使用StreamWriter:
using (var sw = new StreamWriter(path))
{
for (var i = 2; i <= 75; i++)
{
sw.WriteLine("Error_Flag = 'FOR_IMPORT' and location_type = 'Home' and batch_num = {0}", i);
}
}
这将自动创建文件,写下所有行,然后在完成后关闭它。
答案 1 :(得分:1)
不要使用File.WriteAllText,因为每次都会生成一个新文件。
而是尝试这样的事情:
using (var writer = new StreamWriter("filename.txt"))
{
for(int x = 2; x <= 75; x++)
{
writer.WriteLine("Error_Flag = 'FOR_IMPORT' and location_type = 'Home' and batch_num = " + x);
}
}
答案 2 :(得分:0)
您在每次新的写操作时都会覆盖该文件。考虑appending。