title: In C#, if 2 processes are reading and writing to the same file, what is the best way to avoid process locking exceptions?
body: <p>With the following file reading code:</p>
  
  <pre><code>using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None))
  {
      using (TextReader tr = new StreamReader(fileStream))
      {
          string fileContents = tr.ReadToEnd();
      }
  }
  </code></pre>
  
  <p>And the following file write code:</p>
  
  <pre><code>using (TextWriter tw = new StreamWriter(fileName))
  {
      tw.Write(fileContents);
      tw.Close();
  }
  </code></pre>
  
  <p>The following exception details are seen:</p>
  
  <blockquote>
    <p>The process cannot access the file
    'c:\temp\myfile.txt' because it is
    being used by another process.</p>
  </blockquote>
  
  <p>What is the best way of avoiding this? Does the reader need to retry upon receipt of the exception or is there some better way?</p>
  
  <p>Note that the reader process is using a <em>FileSystemWatcher</em> to know when the file has changed.</p>
  
  <p>Also note that, in this instance, I'm <strong>not</strong> looking for alternatives ways of sharing strings between the 2 processes.</p>