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

三世轮回 提交于 2021-02-05 09:30:26

问题


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() sufficient?

class ExampleClass : IDisposable {
    private FileStream stream = File.Open("command-list.txt", FileMode.Append, FileAccess.Write, FileShare.Read);

    public void Execute(string command) {
        var buffer = Encoding.UTF8.GetBytes(command);
        stream.WriteByte(10);
        stream.Write(buffer, 0, buffer.Length);
        stream.Flush(true);
        Process.Start("processor", "command-list.txt");
    }

    public void Dispose() {
        stream.Close();
    }
}

回答1:


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.




回答2:


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

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



来源:https://stackoverflow.com/questions/25255008/do-i-need-to-use-filestream-flush-or-filestream-flushtrue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!