title: Concurrent writing to a file with c#
body: <p>I have an application that is writing to a file concurrently</p>
  
  <p>When it runs to the end, it should be about 100k lines. Right now it I will get the message after 10k records written.</p>
  
  <p><strong>Below is the Error:</strong></p>
  
  <blockquote>
    <p>System.IO.__Error.Void WinIOError(Int32, System.String) - The process cannot access the file 'C:\Temp\xxx.txt' because it is being used by another process.</p>
  </blockquote>
  
  <p>Code:</p>
  
  <pre><code>public class FileExport
  {
      private object lockPathObject = new object();
      private object lockACLbject = new object();
      static string pathHeader = "ScanDate,Path,IsDirectory,Files,Size,Owner,Accessed," +
          "Created,Modified,sourcetype";
      static string aclHeader = "ScanDate,Path,Trustee,Permissions,AccessType,Inherit," + 
          "SID,sourcetype";
      static string sourceType = "EUSFileservice";
  
      private static NamedReaderWriterLockSlim&lt;string&gt; locker = 
          new NamedReaderWriterLockSlim&lt;string&gt;();
  
      public void ExportPath(IEnumerable&lt;PathInfo&gt; paths, string filename)
      {
          try
          {
              // lock (lockPathObject)
              using (locker.LockWrite(filename))
              {
                  using (StreamWriter w = File.AppendText(filename))
                  {
                      if (w.BaseStream.Position == 0)
                          w.WriteLine(pathHeader);
                      foreach (PathInfo path in paths)
                      {
                          if (path == null)
                              continue;
  
                          w.WriteLine("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\"," + 
                              "\"{5}\",\"{6}\",\"{7}\",\"{8}\"", DateTime.UtcNow, 
                              path.Path, (path.IsDirectory ? 1 : 0), path.Files, 
                              path.Size, path.Owner, path.AccessDate, path.CreateDate, 
                              path.ModifiedDate, sourceType);
                      }
  
                      w.Flush();
                  }
              }
          }
          catch(Exception ex)
          {
              ErrorLogger.LogEvent(ex);
          }
          return;
      }
  </code></pre>
  
  <p>I am calling it from </p>
  
  <pre><code>void ProcessTasks()
  {
      FileExport se = new FileExport();
      while (true)
      {
          var pathList = pathQueue.DequeueChunk(20);
  
          se.ExportPath(pathList, pathFileName);
  
          if (pathQueue.Count == 0)
          {
              break;
          }
      }
  }
  </code></pre>
  
  <p>I tried using a lock and <code>NamedReaderWriterLockSlim</code> with the same results. Any suggestions?</p>
  
  <p><strong>Update:</strong>
  The error is happenning at:</p>
  
  <pre><code>using (StreamWriter w = File.AppendText(filename))
  </code></pre>
  
  <p>Stacktrace</p>
  
  <pre><code>at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
     at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
     at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
     at System.IO.StreamWriter.CreateFile(String path, Boolean append, Boolean checkHost)
     at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize, Boolean checkHost)
     at System.IO.StreamWriter..ctor(String path, Boolean append)
     at System.IO.File.AppendText(String path)
  </code></pre>