Reputation: 9194
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?
Upvotes: 2
Views: 6860
Reputation: 56222
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");
}
}
}
Upvotes: 7