如何从C#服务编写日志文件,以便及时刷新到磁盘?
这是我尝试过的。在记录代码中,我打开了一个这样的文件:
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()
有没有更好的方法来强制冲洗?