title: How to handle concurrent file access with a filestream/streamwriter?
body: <p>I am writing an audit file that is writing the username, time, and the old/changed values of several variables in the application for each user when they use my application.  It is using a <code>FileStream</code> and <code>StreamWriter</code> to access the audit file.  All audits for each user will be written to the same file.  </p>
  
  <p>The issue is that when two users are updating this audit file at the same time, the "old value" of each of the variable is mixing up between the users.  Why is this and how can you solve the concurrency problem here?</p>
  
  <p>Some code, shortened for brevity...</p>
  
  <pre><code>Dim fs As FileStream
  Dim w As StreamWriter
  
  Public Sub WriteAudit(ByVal filename As String, ByVal username As String, ByVal oldAddress As String, ByVal newAddress As String, ByVal oldCity As String, ByVal newCity As String)
      Dim now As DateTime = DateTime.Now
      Dim audit As String = ""
      audit += now + "," + username + "," + oldAddress + "," + newAddress + "," + oldCity + "," + newCity
  
      fs = New FileStream(filename, FileMode.Append)
      w = New StreamWriter(fs)
      w.WriteLine(audit)
      w.Close()
      fs.Close()
  End Sub
  </code></pre>
  
  <p>This lives in an AuditLogger class, which is referenced via an instance variable (re-allocated each time the function is accessed).</p>