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?
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With