Paul Hollingsworth Paul Hollingsworth - 1 year ago 143
C# Question

Creating an empty file in C#

What's the simplest/canonical way to create an empty file in C#/.NET?

The simplest way I could find so far is:

System.IO.File.WriteAllLines(filename, new string[0]);

Answer Source

Using just File.Create will leave the file open, which probably isn't what you want.

You could use:

using (File.Create(filename)) ;

That looks slightly odd, mind you. You could use braces instead:

using (File.Create(filename)) {}

Or just call Dispose directly:


Either way, if you're going to use this in more than one place you should probably consider wrapping it in a helper method, e.g.

public static void CreateEmptyFile(string filename)

Note that calling Dispose directly instead of using a using statement doesn't really make much difference here as far as I can tell - the only way it could make a difference is if the thread were aborted between the call to File.Create and the call to Dispose. If that race condition exists, I suspect it would also exist in the using version, if the thread were aborted at the very end of the File.Create method, just before the value was returned...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download