Do I need to use FileStream.Flush() or FileStream.Flush(true)?

前端 未结 2 1047
长发绾君心
长发绾君心 2021-01-28 08:17

In my program, I write a file, then call an external program that reads that file. Do I need Flush(true) to make sure that the data is written entirely to disk, or is Flush() su

相关标签:
2条回答
  • 2021-01-28 08:33

    Neither; you should simply dispose the stream in a using statement.

    Or, better yet, replace the whole thing with File.AppendAllText().

    0 讨论(0)
  • 2021-01-28 08:50

    Calling Dispose, or any kind of Flush, will make it so that other software will see the data that has been written, but it won't guarantee that the data will actually make it all the way to the disk. If e.g. the data is being written to a USB drive and the cable gets unplugged before the data actually gets written, the program will only find out about the problem if uses a Flush(true) or other similar means to ensure that the data has been written before it it's finished. Whether a program should use Flush(true) depends on the application. If the hard drive is not removable and could only fail in cases where failure to write the file would be the least of one's problems, then Flush(true) is not necessary. If a user might yank a USB drive as soon as the program thinks it's done, then Flush(true) may be a good idea.

    0 讨论(0)
提交回复
热议问题