title: Flushing log to disk, exception in VerifyOSHandlePosition
body: <p>How can I write a logfile from a C# service so that it gets flushed to disk in a timely fashion?</p>
  
  <p>Here's what I've tried.  In logging code, I opened a file like this:</p>
  
  <pre><code>var file = return File.Open(name, FileMode.Append, 
                              FileAccess.Write, FileShare.Read);
  var writer = new StreamWriter(file);
  </code></pre>
  
  <p>and wrote to it like this:</p>
  
  <pre><code>writer.WriteLine(msg);
  writer.Flush();
  file.Flush();
  </code></pre>
  
  <p>However the log was not flushed to disk in a timely fashion.  So I tried adding a 5-second timer that does this:</p>
  
  <pre><code>[DllImport("kernel32.dll")]
  static extern bool FlushFileBuffers(IntPtr hFile);
  
  file.Flush();
  var hdl = file.SafeFileHandle;
  FlushFileBuffers(hdl.DangerousGetHandle());
  </code></pre>
  
  <p>This appears to work, but at infrequent intervals I get the following exception:</p>
  
  <pre><code>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()
  </code></pre>
  
  <p>Is there a better way to force the flush?</p>