Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.IO.File.Create locking a file

Tags:

c#

asp.net

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?

like image 621
Chris Avatar asked Jan 13 '11 12:01

Chris


People also ask

How do I lock a file in CS?

Lock a file while Reading/Writing the file data – Approach 2 Lock a file in C# using File. Lock() method . The lock method let you lock a file so another process cannot access the file. This works even if it has read/write access to the file.

How do you create a .NET file?

The Create() method of the File class is used to create files in C#. The File. Create() method takes a fully specified path as a parameter and creates a file at the specified location; if any such file already exists at the given location, it is overwritten.


2 Answers

Try this:

System.IO.File.Create(FullFName).Close();
like image 95
joe Avatar answered Oct 13 '22 17:10

joe


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
}
like image 81
Edwin de Koning Avatar answered Oct 13 '22 17:10

Edwin de Koning