title: C# file is being used by another process
body: <p>I am not sure how can I solve my problem. From time to time I get the error:
  "The process cannot access the file 'xxxx' because it is being used by another proces".</p>
  
  <p>Here is my method where the error happens:</p>
  
  <pre><code>private static void write_history(int index, int time_in_sec, int[] sent_resources)
          {
              string filepath = "Config\\xxx.txt";
              int writing_index = 0;
  
              if (File.Exists(filepath))
              {
                  System.Threading.Thread.Sleep(5000);
                  StreamReader reader = new StreamReader(new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read));
                  string temp = reader.ReadToEnd();
                  reader.Close();
  
                  for (int i = 0; i &lt; 20; i++)
                  {
                      if (temp.IndexOf("&lt;hst_" + i.ToString() + "&gt;") == -1)
                      {
                          writing_index = i;
                          break;
                      }
                  }
              }
  
              System.Threading.Thread.Sleep(5000);
              // write to the file
              StreamWriter writer = new StreamWriter(filepath, true);
              writer.WriteLine("&lt;hst_" + writing_index.ToString() + "&gt;" + DateTime.Now.AddSeconds(time_in_sec).ToString() + "|" + sent_resources[0] + "|" + sent_resources[1] + "|" + sent_resources[2] + "|" + sent_resources[3] + "&lt;/hst_" + writing_index.ToString() + "&gt;");
              writer.Close();
          }
  </code></pre>
  
  <p>And the error I get:</p>
  
  <pre><code>************** Exception Text **************
  System.IO.IOException: The process cannot access the file 'Config\\xxx.txt' because it is being used by another process.
     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)
  </code></pre>