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?
File.Create(_filePath).Close();
.File.Create()
returns an open file which won't be closed until it's finalizer runs as a side-effect of garbage collection, unless you close it explicitly. But you shouldn't need to create it separately like that.File.Create
creates a file and opens a stream. Either use that stream withStreamWriter
or useFile.AppendText
withoutFile.Create