Chris Chris - 10 days ago 6
ASP.NET (C#) Question

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?

Answer

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
}
Comments