What's the simplest/canonical way to create an empty file in C#/.Net? Simplest way I can find so far:
System.IO.File.WriteAllLines(filename, new string[0]);
What's the simplest/canonical way to create an empty file in C#/.Net? Simplest way I can find so far:
System.IO.File.WriteAllLines(filename, new string[0]);
System.IO.File.Create(@"C:\Temp.txt");
As others have pointed out, you should dispose of this object or wrap it in an empty using statement.
using (System.IO.File.Create(@"C:\Temp.txt"));
File.WriteAllText("path", String.Empty);
File.CreateText("path").Close();
Path.GetTempFileName() will create a uniquly named empty file and return the path to it.
If you want to control the path but get a random file name you can use GetRandomFileName to just return a file name string and use it with Create
For example:
string fileName=Path.GetRandomFileName();
File.Create("custom\\path\\" + fileName);
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:
File.Create(filename).Dispose();
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)
{
File.Create(filename).Dispose();
}
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...
You can chain methods off the returned object, so you can immediately close the file you just opened in a single statement.
File.Open("filename", FileMode.Create).Close();