System.IO.File.Create locking a file

I’m using System.IO.File.Create to create a file. I’m not writing to it with a stream writer, just creating it.

I get a server error in the front end when the application tries to open the newly created file – that the file is in use. Garbage collection then seems to come along and a few minutes later all is OK.

Now I know if I was using Streamwriter I would have to close it. Does the same apply to creating?

I’ve read that opening a stream writer to the file then immediately closing it will fix this, but it seems messy. Is there a simpler way?


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Try this:


Method 2

File.Create returns a FileStream. You should use it like this:

using (FileStream fs = File.Create(path))
    //you can use the filstream here to put stuff in the file if you want to

Method 3

Creating the file opens a FileStream to it, hence, locking it (File.Create returns the FileStream).

You must close this stream in order to access the file. This is best done with a using statement:

using(FileStream fs = File.Create(path))

Method 4

When using File.Create you get a FileStream returned. Until you either close the stream or until the FileStream object is disposed (by the garbage collector’s finaliser) it will remain open and locked.

FileStream implements IDisposable so you can do the following:

using(FileStream fs = File.Create(filename))
    // Do stuff like write to the file

The using statement is “syntactic sugar” and causes the compiler to generate code that is functionally equivalent to:
FileStream fs = File.Create(filename)
    // Do stuff like write to the file

The Dispose method calls Close internally.

Method 5

I was using:

The above .Create method was not closing the file

I now use:
System.IO.File.WriteAllText(sFullFileName, "Uploading");

This method creates and closes the file (note: I put a string “Uploading” in the file, but i’m sure string.Empty will also work.

Method 6

The Create method will return a file handle. The file handle should be closed before re-using the file. Please see details in the MSDN article File.Create Method (String).


The FileStream object created by this method has a default FileShare value of None; no other process or code can access the created file until the original file handle is closed.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x