title: filestream fileshare access by 2 process to read and write at the same time
body: <p>I got a primitive website, where the aspx webform and socket server access flat files, which stores the data. The socketserver will be accessing the same exact files to write, which is accessed by the aspx c# code for reading. I think there may be an issue with locking the files. I think it is the higher priority for the server to quick write to the file and release any lock on the file. The webform should be able to read without interrupting the writing process of the server. What is the best way to do this? Is it with the using streamwriter?</p>
  
  <p>The server used this call, to only share file for reading while it is  writing to the file.</p>
  
  <pre><code>                    if (!File.Exists(filepath))
                      {
                          using (FileStream fileStream = new FileStream(filepath, FileMode.CreateNew, FileAccess.Write, FileShare.Read))
                          {
                              using (TextWriter writer = new StreamWriter(fileStream))
                              {
                                  writer.WriteLine(data);
                                  m_clientSocket.Send(BitConverter.GetBytes(data.Length));
                              }
                          }
                      }
                      else
                      {
                          using (FileStream fileStream = new FileStream(filepath, FileMode.Append, FileAccess.Write, FileShare.Read))
                          {
                              using (TextWriter writer = new StreamWriter(fileStream))
                              {
                                  writer.WriteLine(data);
                                  m_clientSocket.Send(BitConverter.GetBytes(data.Length));
                              }
                          }
                      }
  </code></pre>
  
  <p>The webform read with the following command</p>
  
  <pre><code>        using (FileStream stream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read))
          {
              using (TextReader reader = new StreamReader(stream))
              {
                  //string fileContents = tr.ReadToEnd();
                  while ((line = reader.ReadLine()) != null)
                  {
                      if (!string.IsNullOrEmpty(line))
                      {
                          lines.Add(line);
                      }
                  }
              }
          }
  </code></pre>
  
  <p>I am hoping this may work without having to lock the file and manage access, which I am not sure how to do. I want to be able to for the server to lock the file for writing at anytime but also allow the same file to be read by the aspx webpage c# code.</p>
  
  <p>Any help is appreciated.</p>