Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# cannot access file immediately after creating it

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?

like image 278
Jessica Avatar asked Dec 10 '22 03:12

Jessica


1 Answers

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");
}
like image 196
Lana Avatar answered Dec 22 '22 19:12

Lana