System.IO.StreamWriter不会为整个for循环编写 [英] System.IO.StreamWriter doesn't write for entire for loop
问题描述
我正在尝试将一长串数字写入C#中的文件,但是它在列表结尾之前一直停下来.例如下面的代码:
I am trying to write a long list of numbers to a file in C# but it keeps stopping before the end of the list. For example the following code:
System.IO.StreamWriter file = new System.IO.StreamWriter("D:\\test.txt");
for (int i = 0; i < 500; i++)
{
file.WriteLine(i);
}
给我留下一个列出数字0至431的文本文件.将500更改为1000会使我获得0到840的信息.在循环结束之前,它似乎总是停止写入.成功将数字输出到控制台以及文件会在控制台中显示完整列表,但不会显示文件.
Leaves me with a text file listing the numbers 0 to 431. Changing 500 to 1000 gets me 0 to 840. It just always seems to stop writing before the loop is finished. Outputing the numbers to console as well as file successfully gives the full list in the console, but not the file.
推荐答案
您需要在退出程序之前关闭编写器,以确保所有缓冲的输出都已写入文件.
You need to close the writer before exiting your program, to make sure that all the buffered output gets written to the file.
一种非常方便的方法是使用 使用
语句,该语句确保您的循环完成后, StreamWriter
被关闭:
A one very convenient way of doing it is with the using
statement, which ensures that the StreamWriter
gets closed once your loop is done with it:
using (System.IO.StreamWriter file = new System.IO.StreamWriter("D:\\test.txt"))
{
for (int i = 0; i < 500; i++)
{
file.WriteLine(i);
}
}
这篇关于System.IO.StreamWriter不会为整个for循环编写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!