Tuesday, May 3, 2011

Creating an empty file in C#

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]);
From stackoverflow
  • 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"));
    
    kentaromiura : won't be better dispose the object? eg: using (System.IO.File.Create(filepath)) { }
    Jon Skeet : @kentaromiura: My thoughts exactly, hence my answer :)
    Eoin Campbell : Good point guys. will update the orig. Cheers.
    Cloud : I think that last line of code needs another "
  • 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);
    
    kay.herzam : IMHO GetTempFileName() is completely misnamed.
    Crippledsmurf : Why exactly is this answer not helpful?
  • 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...

    Brian Genisio : Funny. I just wrote the same code about 5 minutes ago. I did File.Create(filename).Close(); Same diff...
  • 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();
    
  • //:D
    bool exists = File.Exists("path");
    exists = true;
    
    Paul Hollingsworth : this won't create an empty file - it'll just initialize the boolean "exists" to the value "true"
    Przemek and Piotr : It's a joke man.

0 comments:

Post a Comment