219

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]);

7 Answers 7

441

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

You could use:

// Results in compiler warning "warning CS0642: Possible mistaken empty statement"
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...

11
  • 8
    Funny. I just wrote the same code about 5 minutes ago. I did File.Create(filename).Close(); Same diff... Apr 29, 2009 at 14:43
  • 2
    My code was using using (File.Create(filename)) ;, but I love the simplicity of File.Create(filename).Dispose();
    – Vadim
    Apr 29, 2013 at 16:17
  • 2
    @user3791372: Close() will release the resources as well. Close() just calls Dispose - see github.com/dotnet/coreclr/blob/master/src/mscorlib/src/System/…
    – Jon Skeet
    Mar 7, 2016 at 14:27
  • 3
    It might not be obvious that if the file already exists, and isn't read-only, the file contents are overwritten. To avoid this, use using (new FileStream(filename, FileMode.CreateNew)) { } Nov 23, 2016 at 4:28
  • 1
    @huha: There's no indication that the OP wants to catch any such exception though. I know very often I write tools that expect to be able to create files, and I'd want that exception to just propagate to the top level.
    – Jon Skeet
    Nov 17, 2020 at 10:59
42
File.WriteAllText("path", String.Empty);

or

File.CreateText("path").Close();
5
  • 4
    Using the first, the file is 3 bytes long: the encoding code. Using the second the file is of 0 byte (really empty).
    – Fil
    May 27, 2015 at 21:03
  • 1
    @Fil: Are you sure? The documentation says that File.WriteAllText(string, string) uses "UTF-8 encoding without a Byte-Order Mark (BOM)". If you still see one, that would be a bug in WriteAllText or its documentation worth reporting.
    – Heinzi
    Mar 7, 2017 at 14:09
  • I remember I've tryed. Maybe it was an old bug of previous .Net version? The file is not empty if I specify explicitly to use UTF8 encoding (or unicode or something else): <File.WriteAllText("c:\del.txt", String.Empty, System.Text.Encoding.UTF8);>
    – Fil
    Mar 8, 2017 at 14:54
  • 2
    @Fil, Encoding.UTF8 returns an encoder that outputs the Byte Order Mark (BOM). You can use new UTF8Encoding(false) to get a UTF8 encoder that doesn't output the BOM. May 31, 2017 at 14:03
  • 1
    Don't know if WriteAllText really behaves different in previous version of .NET. However, to be extra sure, just skip the encoding part and use File.WriteAllBytes(path, new byte[] { }); instead. Jun 27, 2017 at 12:48
22
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"));
2
  • 5
    won't be better dispose the object? eg: using (System.IO.File.Create(filepath)) { } Apr 29, 2009 at 14:21
  • @kentaromiura: My thoughts exactly, hence my answer :)
    – Jon Skeet
    Apr 29, 2009 at 14:23
8

To avoid accidentally overwriting an existing file use:

using (new FileStream(filename, FileMode.CreateNew)) {}

...and handle the IOException which will occur if the file already exists.

File.Create, which is suggested in other answers, will overwrite the contents of the file if it already exists. In simple cases you could mitigate this using File.Exists(). However something more robust is necessary in scenarios where multiple threads and/or processes are attempting to create files in the same folder simultaneously.

1
  • 1
    Agreed, doing if (!File.Exists(file)) // then create file is an antipattern that a lot of devs follow. Much better to do the create and catch any exception instead, thus making your code more thread safe.
    – bytedev
    Sep 23, 2021 at 9:06
4

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();
3

A somewhat common use case for creating an empty file is to trigger something else happening in a different process in the absence of more sophisticated in process communication. In this case, it can help to have the file creation be atomic from the outside world's point of view (particularly if the thing being triggered is going to delete the file to "consume" the trigger).

So it can help to create a junk name (Guid.NewGuid.ToString()) in the same directory as the file you want to create, and then do a File.Move from the temporary name to your desired name. Otherwise triggered code which checks for file existence and then deletes the trigger may run into race conditions where the file is deleted before it is fully closed out.

Having the temp file in the same directory (and file system) gives you the atomicity you may want. This gives something like.

public void CreateEmptyFile(string path)
{
    string tempFilePath = Path.Combine(Path.GetDirectoryName(path),
        Guid.NewGuid.ToString());
    using (File.Create(tempFilePath)) {}
    File.Move(tempFilePath, path);
}
0

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);
4
  • IMHO GetTempFileName() is completely misnamed.
    – kay.herzam
    Apr 29, 2009 at 14:26
  • Why exactly is this answer not helpful? Apr 30, 2009 at 20:39
  • 6
    It's unhelpful for two reasons: 1. The question doesn't ask anything about generating a random file name, so that's a distraction. 2. The file does not get closed, which means that if you later try to open another file writer, or move the file, it will fail. Dec 8, 2015 at 4:59
  • I take your points but: 1. All files need a name. That was a simple. convenient way to get one that wasn't likely to collide with anything 2. The question asked about creating files, which the code in question does, minimally, management of the file thereafter is not strictly part of creation, so I omitted it for the sake of simplicity and keeping the answer focused on the question Dec 10, 2015 at 5:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.