C# – How to create a file and write to it

There are a few ways to create a file and write to it using the .NET File API (in System.IO). The simplest way is to use high-level methods like File.WriteAllText() and File.WriteAllLines(), specifying the file path and string(s) to write to the file. Here’s an example of using these (and their async equivalents):

using System.IO;

//Create a file and write the string
File.WriteAllText(@"C:\temp\a.txt", "Hello World");

var lines = new List<string>() { "Hello", "World" };
//Create a file and write strings as lines
File.WriteAllLines(@"C:\temp\b.txt", lines);

//Async versions
await File.WriteAllTextAsync(@"C:\temp\a_async.txt", "Hello World Async");

await File.WriteAllLinesAsync(@"C:\temp\b_async.txt", lines);
Code language: C# (cs)

These high-level methods abstract away the details. They create the file, open it for writing, write the content, and then close the file. If the file already exists, they overwrite it.

The next best option is to use File.CreateText(). This returns a StreamWriter, which you can use to write to the file. Here’s an example:

using System.IO;

//Create a new text file and write content
using (StreamWriter writer = File.CreateText(@"C:\temp\b.txt"))
    writer.WriteLine("Hello World");
Code language: C# (cs)

This creates the text file, opens it for writing, writes each line, and then closes the file (when it falls out of the using block). If the file already exists, this overwrites it. Here’s what the file content looks like:

Hello World
Code language: plaintext (plaintext)

I’ll show examples of less common scenarios (like writing to a binary file), and also discuss some problems to avoid.

Exception when the directory doesn’t exist

If you try to create a file in a non-existing directory, you’ll get an exception like this:

System.IO.DirectoryNotFoundException: Could not find a part of the path ‘C:\data\en\hello.txt’.

You can use Directory.CreateDirectory() to create the missing directories. Pass in the directory path (without the file name), and it’ll create all missing directories in the path. Here’s an example (C:\data\ and C:\data\en\ are missing):

using System.IO;

var filePath = @"C:\data\en\hello.txt";

var directory = Path.GetDirectoryName(filePath);

File.WriteAllText(filePath, "Hello new directory");
Code language: C# (cs)

This first creates the C:\data\ and C:\data\en\ directories, and then creates the file in C:\data\en\ and writes to it.

Note: If the directory already exists, Directory.CreateDirectory() does nothing.

Create a file in the current directory

You can specify a relative or absolute file path when creating a file. If you specify just a file name, it’ll create the file in the current directory (whatever Environment.CurrentDirectory is set to).

Here’s an example:

using System.IO;

Console.WriteLine("Current directory:");

File.WriteAllText("new.txt", "Created in cur dir");

var filePath = Path.Combine(Environment.CurrentDirectory, "new.txt");
Console.WriteLine($"Does the file exist? {File.Exists(filePath)}");
Code language: C# (cs)

This outputs:

Current directory:

Does the file exist? TrueCode language: plaintext (plaintext)

Create and write to a binary file

Most of the time you’ll be dealing with text files, but sometimes you may need to create and write to binary files. The two simplest ways to do this are to use File.WriteAllBytes() or use File.Create() and BinaryWriter. These are equivalent to the text file methods I showed up above.

Here’s an example of writing a byte array to a binary file with File.WriteAllBytes():

using System.IO;

byte[] data = new byte[]
    //ASCII 'hello'

File.WriteAllBytes(@"C:\temp\data.bin", data);
Code language: C# (cs)

This creates a binary file with the ASCII bytes for “hello” in it.

The other option is to use File.Create() to create the file. This returns a FileStream. You can then use BinaryWriter to write data to the FileStream. Here’s an example:

using System.IO;

using (var writer = new BinaryWriter(File.Create(@"C:\temp\hello.bin")))
    writer.Write("Hello World");
Code language: C# (cs)

This creates a binary file and writes bytes for whatever objects you pass it.

Note: If you open it up in Notepad++, you can see the unprintable characters, like [NUL].

Leave a Comment