Reputation: 2051
I have a scenario where I need to check if a txt file exists, if it doesn't I need to create it.
Immediately after this, I need to populate the file with some text.
This is what my code looks like:
if (!File.Exists(_filePath))
{
File.Create(_filePath);
}
using (var streamWriter = File.AppendText(_filePath))
{
//Write to file
}
I receive an exception (System.IO.IOException
) on line 5, only when a new file has to be created. Here is the exception:
The process cannot access the file '**redacted file path**' because it is being used by another process.
I don't want to add something like Thread.Sleep(1000);
, as that is an awful solution.
Is there a way to find out when the file is free again, so that I can write to it?
Upvotes: 4
Views: 2135
Reputation: 51
FileCreate method return Filestream which should be closed before using StreamWriter
if (!File.Exists(_filePath))
{
// close fileStream
File.Create(_filePath).Close();
}
using (var streamWriter = File.AppendText(_filePath))
{
//Write to file
}
Upvotes: 5
Reputation: 1046
Just use StreamWriter with param append = true
. It'll create the file if needed.
using (StreamWriter sw = new StreamWriter(_filePath, true, Encoding.Default))
{
sw.WriteLine("blablabla");
}
Upvotes: 6
Reputation: 9519
You were so close, just remove the first if
, the File.AppendText
will do the trick for you and create file if not there.
using (var streamWriter = File.AppendText(_filePath))
{
//write to file
}
Upvotes: 4