Ad

"System.IO.IOException: The Process Cannot Access The File 'C:\Test\test.txt' Because It Is Being Used By Another Process"

- 1 answer

Pretty new to C#. Trying to iteratively write to a .txt file and I tried to use this to implement the solution:

Create a .txt file if doesn't exist, and if it does append a new line

I have it written as such:

  var path = @"C:\Test\test.txt";

  try
  {
    if (!File.Exists(path))
    {
      File.Create(path);
      TextWriter tw = new StreamWriter(path);
      tw.WriteLine(message);
      tw.Close();
    }
    else if (File.Exists(path))
    {
      using (var tw = new StreamWriter(path, true))
      {
        tw.WriteLine(message);
        tw.Close();
      }
    }
  }
  catch (Exception e)
  {
    Console.WriteLine(e);
    throw;
  }
}

Whether or not the file exists, it generates the same error:

"System.IO.IOException: The process cannot access the file 'C:\Test\test.txt' because it is being used by another process"

What am I doing wrong this time?

Ad

Answer

File.Create(path); opens the file and leaves it opened. When you do TextWriter tw = new StreamWriter(path); you are trying to access the file which is being used by the process which created the file (the code line above).

You should do something like this:

if (!File.Exists(path))
{
    using (var stream = File.Create(path))
    {
        using (TextWriter tw = new StreamWriter(stream))
        {
            tw.WriteLine("abc");
        }
    }
}
Ad
source: stackoverflow.com
Ad