Jon
Jon

Reputation: 2584

Wait for a file to be created before writing to it

I have this code:

if (!File.Exists(fileName))
{
    File.Create(fileName);
}
File.WriteAllText(fileName, contents);

However, every time I run it I get an IOException:

An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll

Additional information: The process cannot access the file 'C:\Users\Frankie\Commander\config\freq.txt' because it is being used by another process.

How do I make the File.WriteAllText() wait until it's done being created?

Upvotes: 0

Views: 288

Answers (2)

Yair Nevet
Yair Nevet

Reputation: 13003

Close the file after creating it:

if (!File.Exists(fileName))
{
    File.Create(fileName).Close();
}
File.WriteAllText(fileName, contents);

Upvotes: 0

Grant Winney
Grant Winney

Reputation: 66439

The WriteAllText method creates the file for you, so this is all you need:

if (!File.Exists(fileName))
{
    File.WriteAllText(fileName, contents);
}

If you don't care about potentially overwriting the file, you could even omit the File.Exists check, as WriteAllText will overwrite an existing file.

The reason you're having a problem with your original code is that File.Create opens a FileStream for the file, and so locks it; you'd have to close it first before you could write to it.

Upvotes: 2

Related Questions