2012-02-08 50 views
1

如何从C#服务写入日志文件以便及时刷新到磁盘?将日志刷新到磁盘,VerifyOSHandlePosition中的异常

这是我试过的。在日志记录代码,我开这样的文件:

var file = return File.Open(name, FileMode.Append, 
          FileAccess.Write, FileShare.Read); 
var writer = new StreamWriter(file); 

,并写信给它这样的:

writer.WriteLine(msg); 
writer.Flush(); 
file.Flush(); 

但是及时日志没有刷新到磁盘。所以,我想补充说,这是否一个5秒定时器:

[DllImport("kernel32.dll")] 
static extern bool FlushFileBuffers(IntPtr hFile); 

file.Flush(); 
var hdl = file.SafeFileHandle; 
FlushFileBuffers(hdl.DangerousGetHandle()); 

这似乎工作,但不频繁的间隔,我得到以下异常:

System.IO.IOException: The OS handle's position is not what FileStream expected. Do not use a handle simultaneously in one FileStream and in Win32 code or another FileStream. This may cause data loss. 

at System.IO.FileStream.VerifyOSHandlePosition() 

有没有更好的办法来迫使冲洗?

回答

0

this answer,在.NET 4.0这是不够的,只是叫

file.Flush(true) 

与p乱搞/ Invoke调用不再需要。

+1

MS bug report [here](http://connect.microsoft.com/VisualStudio/feedback/details/634385/filestream-flush-flushtodisk-true-call-does-not-flush-the-buffers-to-磁盘#细节)说file.Flush(真)已损坏,然后修复,但没有说明它修复了哪个版本或服务包!听起来像bug是如果内部的.NET FileStream缓冲区是空的,Flush(true)什么也没做? – jimvfr 2012-11-09 02:34:22