问题描述
在我的程序中,我编写了一个文件,然后调用一个读取该文件的外部程序.我是否需要 Flush(true)代码>
,以确保将数据完全写入磁盘或 Flush()
足够?
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();
}
}
推荐答案
调用 Dispose
或任何类型的 Flush
都会使它起作用,以便其他软件可以看到但是不能保证已写入的数据确实会一直到达磁盘.如果例如如果将数据写入USB驱动器,并且在实际写入数据之前拔掉了电缆,则只有使用 Flush(true)
或其他类似方法来确保该程序能够发现问题,数据在完成之前已被写入.程序是否应使用 Flush(true)
取决于应用程序.如果硬盘驱动器不可移动,并且只有在写文件失败是最小问题的情况下才会发生故障,则不需要 Flush(true)
.如果用户在程序认为完成后立即拉动USB驱动器,那么 Flush(true)可能是个好主意.
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.
这篇关于我是否需要使用FileStream.Flush()或FileStream.Flush(true)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!