C# System.IO.StreamWriter不';不为整个for循环写入

C# System.IO.StreamWriter不';不为整个for循环写入,c#,for-loop,streamwriter,C#,For Loop,Streamwriter,我正试图用C#将一长串数字写入一个文件,但它总是在列表结束前停止。例如,以下代码: System.IO.StreamWriter file = new System.IO.StreamWriter("D:\\test.txt"); for (int i = 0; i < 500; i++) { file.WriteLine(i); } System.IO.StreamWriter file=new System

我正试图用C#将一长串数字写入一个文件,但它总是在列表结束前停止。例如,以下代码:

  System.IO.StreamWriter file = new System.IO.StreamWriter("D:\\test.txt");

        for (int i = 0; i < 500; i++)
        {
            file.WriteLine(i);
        }
System.IO.StreamWriter file=new System.IO.StreamWriter(“D:\\test.txt”);
对于(int i=0;i<500;i++)
{
文件写入线(i);
}

留给我一个文本文件,上面列出了0到431的数字。将500改为1000会使我得到0到840。它似乎总是在循环完成之前停止写入。成功地将数字输出到控制台和文件会在控制台中显示完整列表,但不会显示文件。

您需要在退出程序之前关闭编写器,以确保所有缓冲输出都写入文件

一种非常方便的方法是使用语句,它确保
StreamWriter
在循环完成后关闭:

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文件=新的System.IO.StreamWriter(“D:\\test.txt”))
{
对于(int i=0;i<500;i++)
{
文件写入线(i);
}
}

StreamWriter是缓冲的,这意味着它不会在每次调用write时写入文件

由于您自己没有关闭StreamWriter,因此依赖对象的终结器来刷新缓冲区中的剩余字节


更改代码以将StreamWriter放入using语句中,一旦using块退出,内容将被刷新

您发现StreamWriter使用了一个4096字节长的缓冲区进行输出。此缓冲区有助于提高效率,减少对操作系统WriteFile()函数的调用次数。要确保缓冲区内容进入文件,需要调用Flush()方法或使用Close()或Dispose()关闭流

如果确定要保持文件处于打开状态,则可以添加以下代码行,以确保在写入文件时可以看到输出:

    file.AutoFlush = true;
默认情况下,文件的“自动刷新”属性为false。对于控制台也是如此,这就是为什么可以立即看到Console.Write/Line()的输出。这也是控制台输出如此缓慢的原因之一


但是考虑到您的文件变量是一个局部变量,您几乎肯定只想关闭文件。使用using语句确保在包含此代码的方法返回时处理好。忘记这样做会使文件打开一段时间,至少在下一次垃圾收集之前。

提醒Windows用户:在写入流时,不要忘记刷新。比如当你去洗手间,把东西放进马桶,你也会冲,对吗?