System.IO.File.Create locking a file
C#asp.netC# Problem Overview
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?
C# Solutions
Solution 1 - C#
Try this:
System.IO.File.Create(FullFName).Close();
Solution 2 - C#
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
}
Solution 3 - C#
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))
{
}
Solution 4 - C#
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)
try
{
// Do stuff like write to the file
}
finally
{
fs.Dispose();
}
The Dispose
method calls Close
internally.
Solution 5 - C#
I was using:
System.IO.File.Create(sFullFileName);
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.
Solution 6 - C#
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).
Summary:
> 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.