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?