skip to content
Khalid Abuhakmeh logo Khalid Abuhakmeh

C# Write to File: WriteAllText, WriteAllLines, AppendAllText, and StreamWriter

How to write to a file in C# with File.WriteAllText, WriteAllLines, WriteAllBytes, AppendAllText, async methods, and StreamWriter, with tested examples.

5 min read
A blank page ready for writing, representing writing data to a file. Photo by Clay Banks on Unsplash.

Quick answer

To write to a file in C#, call File.WriteAllText(path, text) to write a string, File.WriteAllLines for a collection of lines, or File.WriteAllBytes for binary data. Use File.AppendAllText to add to the end of a file instead of overwriting it, the WriteAll*Async variants in async code, and StreamWriter when you need to stream a large file or control the write.

To write to a file in C#, call File.WriteAllText(path, text) to write a string, File.WriteAllLines for a collection of lines, or File.WriteAllBytes for binary data. Use File.AppendAllText to add to the end of a file instead of overwriting it, the async variants (WriteAllTextAsync and friends) in async code, and StreamWriter when you need to stream a large file or control exactly how data is written.

The code samples in this post were compiled and run in a scratch console project on the .NET SDK installed on my machine. They only use long-standing System.IO APIs, so they apply to .NET 10 / C# 14 as well. If you’re looking for advice about reading files, I’ve written a post titled reading a file in C#.

When you’re not sure which method to reach for in your codebase, use my quick decision guide:

You want to… Use Notes
Write a whole string File.WriteAllText Creates the file or overwrites it
Write many lines File.WriteAllLines Accepts string[] or IEnumerable<string>
Write raw bytes (images, binary formats) File.WriteAllBytes Takes a byte[]
Add to the end of a file File.AppendAllText / AppendAllLines Creates the file if missing; never overwrites
Stream a large file or write in pieces StreamWriter Most control, flat memory use
Any of the above without blocking WriteAllTextAsync, WriteAllBytesAsync, WriteAllLinesAsync, AppendAllTextAsync Use in async code and web apps

How do you write a string to a file in C#?

File.WriteAllText is the simplest way to write to a file in C#. It opens (or creates) a target file, writes the string, and closes it for you. The default encoding is UTF-8 without a byte order mark (BOM).

File.WriteAllText("hello.txt", "Hello, file!");

If hello.txt already exists, its contents are replaced. If it doesn’t, it is created. That’s all you need for config files, small exports, and quick scripts.

How do you write multiple lines to a file in C#?

File.WriteAllLines writes each element of a collection as its own line, using the platform’s newline character. In C#, Environment.NewLine resolves to \r\n on Windows and \n on macOS/Linux. It accepts a string[] or any IEnumerable<string>, so you can pipe a LINQ query straight in.

string[] lines = ["one", "two", "three"];
File.WriteAllLines("lines.txt", lines);
IEnumerable<string> rows = Enumerable.Range(1, 3).Select(i => $"Row {i}");
File.WriteAllLines("rows.txt", rows);

Like WriteAllText, it creates the file or overwrites an existing one.

How do you write binary data to a file in C#?

Use File.WriteAllBytes when your data isn’t text: images, serialized payloads, or a proprietary format.

byte[] bytes = [0x48, 0x69, 0x21];
File.WriteAllBytes("data.bin", bytes);

The whole array is in memory before it’s written, so for very large binary output, write through a FileStream in chunks instead.

How do you append to a file instead of overwriting it?

File.AppendAllText adds text to the end of a file and creates the file if it doesn’t exist. File.AppendAllLines does the same for a collection of lines. They’re ideal for logs.

File.AppendAllText("app.log", $"{DateTime.UtcNow:O} started{Environment.NewLine}");
File.AppendAllLines("app.log", ["first", "second"]);

Remember that AppendAllText does not add a newline for you; include Environment.NewLine (or use AppendAllLines) if you want each entry on its own line.

Does File.WriteAllText overwrite the file, and what if the folder doesn’t exist?

Every WriteAll* method creates the file if needed and overwrites it if it exists. Only the Append* methods preserve existing content. What none of them do is create missing directories: writing to logs/app.log when logs doesn’t exist throws a DirectoryNotFoundException. Create the folder first. Directory.CreateDirectory is safe to call when the folder already exists.

Directory.CreateDirectory("out/logs");
File.WriteAllText("out/logs/app.log", "ready");

When should you use StreamWriter to write a file in C#?

Use StreamWriter when the file is large, when you produce data incrementally, or when you need control over encoding, buffering, or append mode. Instead of building one giant string, you write pieces as you go, so memory stays flat.

using var writer = new StreamWriter("big.txt", append: false);
for (var i = 0; i < 1000; i++)
{
writer.WriteLine($"Line {i}");
}

The using declaration flushes and closes the file when the scope ends. Pass append: true to add to an existing file. In async code, prefer await using and WriteLineAsync:

await using var writer = new StreamWriter("async.txt");
await writer.WriteLineAsync("hi");

How do you write a file asynchronously in C#?

Each WriteAll* and AppendAll* method has an async counterpart that returns a Task, so you don’t block a thread on disk I/O. Use these variants in web apps, UI handlers, and any async method.

using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
var ct = cts.Token;
await File.WriteAllTextAsync("a.txt", "x", ct);
await File.WriteAllBytesAsync("a.bin", [0x48, 0x69, 0x21], ct);
await File.WriteAllLinesAsync("lines.txt", ["one", "two"], ct);
await File.AppendAllTextAsync("a.txt", "y", ct);

Every one of these methods accepts an optional CancellationToken, so you can honor timeouts and user cancellation. If you need a guide on reading files, my post on reading a file in C# covers the matching ReadAll*Async methods. Error handling for I/O failures deserves its own guide; see my post on C# exception handling with try/catch.

Frequently Asked Questions

How do I write a string to a text file in C#?

Call File.WriteAllText("path.txt", "your text"). It creates the file if it doesn’t exist, overwrites it if it does, and closes it automatically. In async code use await File.WriteAllTextAsync("path.txt", "your text").

How do I append to a file instead of overwriting it?

Use File.AppendAllText("path.txt", "more text") or File.AppendAllLines for several lines. Both add to the end and create the file when it’s missing. With StreamWriter, pass append: true to the constructor.

How do I write a file asynchronously in C#?

Use await File.WriteAllTextAsync(path, text), WriteAllBytesAsync, WriteAllLinesAsync, or AppendAllTextAsync. Each takes an optional CancellationToken. For streaming, use await using var writer = new StreamWriter(path) and await writer.WriteLineAsync(...).

How do I write binary data to a file in C#?

Pass a byte[] to File.WriteAllBytes("data.bin", bytes), or use File.WriteAllBytesAsync in async code. For files too large to hold in memory, write chunks through a FileStream.

Conclusion

Writing to a file in C# is mostly a matter of picking the right method: File.WriteAllText, WriteAllLines, and WriteAllBytes for whole-file writes, AppendAllText for logs and additions, the async variants for non-blocking code, and StreamWriter when size or control matters. Remember that WriteAll* overwrites, and create your directories first. For the other half of the story, head over to reading a file in C#, and I hope this post helps you ship your next file-writing feature.

Comments

Related Posts