为什么我只能在循环结束时看到我的 StreamWriter 行

Why i can see my StreamWriter lines only at the end of my loop

我有简单的 console applicationlist 个文件。 在我的 list 上的每个循环我都想将当前文件名写入简单的 txt file:

String path = @"C:\log.txt"; // location whre to save my txt file
List<string> files = new List<string>(); // my files list
using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write))
using (StreamWriter sw = new StreamWriter(fs))
{
     foreach (string file in files)
     {
         sw.WriteLine(file);
     }
 }
  1. 为什么我只能看到在循环结束时写入的行?
  2. 如果我的应用程序在循环中间崩溃会怎样?我的日志文件将为空?

Why i can see the lines that written only at the end of my loop.

因为文件仅在 StreamWriter.Dispose 运行后刷新到磁盘,在您的 using 语句结束时。同时,它被缓冲在内存中。

What would happen if my application will crash at the middle of the loop ? my log files will be empty ?

这取决于您的程序何时终止以及流在该特定时刻所处的状态。如果它能够完成并刷新到磁盘,您将看到日志文件。

如果您担心这段代码可能会由于某些预期错误而导致您的应用程序崩溃,请将您的代码包装在 try-catch 块中,并处理这些异常。

StreamWriter 出于性能原因缓冲其输出。如果内部缓冲区中有足够的字节,如果您调用 Flush() 或者如果流被关闭/处置,它将写入文件。

如果您希望输出立即显示,您必须在写入 sw 的每一行之后添加对 sw.Flush() 的调用。