Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a file only if doesn't exists

Tags:

c#

.net

io

I want to create a file ONLY if it doesn't already exists.
A code like:

if (!File.Exists(fileName))
{
    fileStream fs = File.Create(fileName);
}

Leave it open for a race-condition in case the file will be created between the "if" to the "create".

How can I avoid it?

EDIT:
locks can't be used here because it's a different processes (multiple instances of the same application).

like image 276
Roee Gavirel Avatar asked Oct 24 '11 07:10

Roee Gavirel


3 Answers

You can also use

FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate);

However, you should look into thread locking as if more than one thread tries to access the file you'll probably get an exception.

like image 103
Kristian Fenn Avatar answered Oct 11 '22 14:10

Kristian Fenn


Kristian Fenn answer was almost what I needed, just with a different FileMode. This is what I was looking for:

FileStream fs = new FileStream(fileName, FileMode.CreateNew);
like image 20
Roee Gavirel Avatar answered Oct 11 '22 14:10

Roee Gavirel


Is this not a better solution. Also notice the using(var stream...) Use it to close the stream to avoid IO Exceptions.

if (!File.Exists(filePath))
{
    using (var stream = File.Create(filePath)) { }
}
like image 20
JustLearning Avatar answered Oct 11 '22 14:10

JustLearning