问题
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