Ste*_*tze 20 .net c# flush filestream
据我所知,.NET FileStream的Flush方法只将当前缓冲区写入磁盘,但依赖于Windows的磁盘驱动程序和硬盘固件,这并不能保证数据实际上是物理写入磁盘的.
是否有.NET或Win32方法可以给我这个保证?因此,如果在调用此方法后一纳秒之后出现断电,我仍然可以确定一切正常吗?
jim*_*vfr 17
斯蒂芬S.说:
据我所知,.NET FileStream的Flush方法只将当前缓冲区写入磁盘
不,.NET FileStream的Flush只将.NET缓冲区写入操作系统缓存,它不会将操作系统缓存刷新到磁盘.可悲的是,这个类的MSDN文档并没有这么说.对于.NET <4.0,你必须调用Flush + Win32的FlushFilebuffers:
using System.Runtime.InteropServices;
. . .
// start of class:
[DllImport("kernel32", SetLastError=true)]
private static extern bool FlushFileBuffers(IntPtr handle);
. . .
stream.Flush(); // Flush .NET buffers to OS file cache.
#pragma warning disable 618,612 // disable stream.Handle deprecation warning.
if (!FlushFileBuffers(stream.Handle)) // Flush OS file cache to disk.
#pragma warning restore 618,612
{
Int32 err = Marshal.GetLastWin32Error();
throw new Win32Exception(err, "Win32 FlushFileBuffers returned error for " + stream.Name);
}
Run Code Online (Sandbox Code Playgroud)
对于.NET 4.0,您可以改为使用新的flush(true)方法.11/09/2012更新:这里的 MS错误报告说它已损坏,然后修复,但没有说明它修复了哪个版本或服务包!听起来像bug是内部.NET FileStream缓冲区为空,Flush(true)什么也没做?
归档时间: |
|
查看次数: |
16335 次 |
最近记录: |