Search code examples
c#.net.net-coreasp.net-core-webapi.net-core-2.2

.NET Core - Multiple read/write operations on a text file


Multiple read/write operation are access a single file, and while write operation I'm facing this issue

The process cannot access the file because it is being used in another process

Using this to add text to file

using (StreamWriter writer=System.IO.File.AppendText("wwwroot/Files/file.txt"))
      {
           writer.WriteLine(stringData.ToString());
           writer.Close();
      }

Is there anyway to perform multiple read/write on a file?

Thanks


Solution

  • If are using the same code from multiple threads or apps writing to the same file, you may find when one thread is wiring it finds the file already in use. The only reason for the error message is that the file is not closed.

    If the calls to write to the file are sequential from the same app then the file is not getting closed properly.

    One way to handle this is to check for locked files and retry later. something like this can be used to check if the file is open:

    public static bool CanBeOpenedForExclusiveRead(string filename)
            {
                try
                {
                    // Test file for exclusive read/write
                    using (System.IO.FileStream fileStream = System.IO.File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None))
                    {
                        fileStream.Close();
                    }
                    return true;
                }
                catch
                {
                }
    
                return false;
            }
    

    if you are already using something like NLog is to use nlog to "log" writes to a file, where nlog will have better handling of these issues across threads.