C# Write to Text File
To write text to a file in C#, use the methods in the System.IO namespace. File.WriteAllText() is suitable for one string, File.WriteAllLines() writes a collection of lines, and StreamWriter gives you more control when writing content one line at a time.
These methods create the file when it does not exist. By default, the examples in this tutorial overwrite an existing file with the same path. To add content without replacing the current contents, use an append method such as File.AppendAllText(), File.AppendAllLines(), or a StreamWriter opened in append mode.
Choose a C# File-Writing Method
| Method | Use it when | Existing file behavior |
|---|---|---|
File.WriteAllText() | You have one string to save | Overwrites the file |
File.WriteAllLines() | You have multiple lines in an array or collection | Overwrites the file |
StreamWriter | You want to write gradually or control each line | Overwrites by default; can append |
File.AppendAllText() | You want to add text to the end of a file | Preserves existing content |
Example 1 – Write Multiple Lines with System.IO.File.WriteAllLines()
System.IO.File.WriteAllLines() writes each string in an array as a separate line in the specified text file.
Program.cs
using System;
namespace CSharpExamples {
class Program {
static void Main(string[] args) {
string[] lines = { "Hello World.", "Welcome to C# Tutorial.", "TutorialKart." };
try{
System.IO.File.WriteAllLines(@"D:\lines.txt", lines);
Console.WriteLine("Lines written to file successfully.");
} catch(Exception err) {
Console.WriteLine(err.Message);
}
}
}
}
Output
PS D:\workspace\csharp\HelloWorld> dotnet run
Lines written to file successfully.
D:\lines.txt
Hello World.
Welcome to C# Tutorial.
TutorialKart.
The method accepts a file path and an enumerable collection of strings. Each string is followed by the platform-specific line-ending sequence.
Example 2 – Write One String with System.IO.File.WriteAllText()
System.IO.File.WriteAllText() writes one string to the file specified by the path argument. It is useful when the complete text is already available in memory.
Program.cs
using System;
namespace CSharpExamples {
class Program {
static void Main(string[] args) {
string str = "Hello World. Welcome to C# Tutorial. TutorialKart.";
try{
System.IO.File.WriteAllText(@"D:\sample.txt", str);
Console.WriteLine("String written to file successfully.");
} catch(Exception err) {
Console.WriteLine(err.Message);
}
}
}
}
Output
PS D:\workspace\csharp\HelloWorld> dotnet run
String written to file successfully.
D:\sample.txt
Hello World. Welcome to C# Tutorial. TutorialKart.
To include line breaks in a single string, use Environment.NewLine, an interpolated raw string in supported C# versions, or a collection with WriteAllLines().
Example 3 – Write Lines with StreamWriter and a Loop
In the following example, a StreamWriter writes each item in the string array to the file. This approach is useful when each line must be processed or formatted before it is written.
Program.cs
using System;
namespace CSharpExamples {
class Program {
static void Main(string[] args) {
string[] lines = { "Hello World.", "Welcome to C# Tutorial.", "TutorialKart." };
try{
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(@"D:\lines.txt")) {
foreach (string line in lines) {
file.WriteLine(line);
}
}
Console.WriteLine("Lines written to file successfully.");
} catch(Exception err) {
Console.WriteLine(err.Message);
}
}
}
}
Output
PS D:\workspace\csharp\HelloWorld> dotnet run
Lines written to file successfully.
D:\lines.txt
Hello World.
Welcome to C# Tutorial.
TutorialKart.
The using statement disposes the writer when the block ends. This flushes buffered text and releases the file handle even if an exception occurs inside the block.
Append Text Without Overwriting the Existing C# File
File.WriteAllText(), File.WriteAllLines(), and the default StreamWriter constructor replace existing file contents. Use File.AppendAllText() when new text should be added at the end.
using System;
using System.IO;
class Program
{
static void Main()
{
string path = @"D:\log.txt";
string entry = $"Application started at {DateTime.Now}{Environment.NewLine}";
File.AppendAllText(path, entry);
Console.WriteLine("Text appended successfully.");
}
}
For repeated writes, open one StreamWriter in append mode instead of calling an append method many times.
using System.IO;
string path = @"D:\log.txt";
using StreamWriter writer = new StreamWriter(path, append: true);
writer.WriteLine("First appended line.");
writer.WriteLine("Second appended line.");
Write a C# Text File with UTF-8 Encoding
Specify an encoding when the file must use a particular character encoding. The following example writes UTF-8 text explicitly.
using System.IO;
using System.Text;
string path = @"D:\message.txt";
string text = "Hello, नमस्ते, こんにちは";
File.WriteAllText(path, text, Encoding.UTF8);
Explicit encoding is helpful when another application expects a known format or when the text contains characters outside basic ASCII.
Write to a File Asynchronously in C#
In an asynchronous application, use File.WriteAllTextAsync() or File.WriteAllLinesAsync() so the calling thread does not remain blocked while the file operation completes.
using System;
using System.IO;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
string path = @"D:\async-sample.txt";
string text = "This text was written asynchronously.";
await File.WriteAllTextAsync(path, text);
Console.WriteLine("File written asynchronously.");
}
}
Asynchronous file methods are most useful in UI applications, web applications, and other code where blocking the current thread would delay unrelated work.
Create the Target Directory Before Writing the File
File-writing methods create the file, but they do not create missing directories in the path. Use Directory.CreateDirectory() before writing when the target folder may not exist.
using System.IO;
string directory = @"D:\reports";
string path = Path.Combine(directory, "summary.txt");
Directory.CreateDirectory(directory);
File.WriteAllText(path, "Monthly summary");
Directory.CreateDirectory() is safe to call when the directory already exists.
Handle Common C# File-Writing Errors
File operations can fail because the path is invalid, access is denied, the directory is missing, the file is locked, or the storage device is unavailable. Catch specific exceptions when the program can respond differently to each failure.
using System;
using System.IO;
string path = @"D:\sample.txt";
try
{
File.WriteAllText(path, "Sample content");
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("The application does not have permission to write this file.");
}
catch (DirectoryNotFoundException)
{
Console.WriteLine("The target directory does not exist.");
}
catch (IOException ex)
{
Console.WriteLine($"The file could not be written: {ex.Message}");
}
For reusable application code, avoid catching Exception unless you rethrow it or have a clear fallback. Specific exception types make failures easier to diagnose.
Use Portable File Paths in C# Applications
The original examples use absolute Windows paths such as D:\sample.txt. For code that must run on different operating systems, build paths with Path.Combine() and a suitable base directory.
using System;
using System.IO;
string path = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"sample.txt"
);
File.WriteAllText(path, "Portable path example");
Console.WriteLine(path);
This avoids hard-coding path separators and drive letters that may not exist on another computer.
C# Write to Text File FAQs
Does File.WriteAllText() overwrite an existing file?
Yes. If the target file already exists, File.WriteAllText() replaces its contents. Use File.AppendAllText() to preserve the current content and add new text.
What is the difference between WriteAllText() and WriteAllLines()?
WriteAllText() writes one string. WriteAllLines() writes a sequence of strings and places each item on a separate line.
Why does C# fail when the output folder does not exist?
The file-writing methods can create a file, but not missing parent directories. Create the folder first with Directory.CreateDirectory().
When should StreamWriter be used instead of File.WriteAllText()?
Use StreamWriter when content is produced gradually, when you need repeated writes, when you want to append through one open writer, or when each line requires custom processing.
C# Text File Writing Summary
In this C# Tutorial, we learned how to write a string or a collection of lines to a text file. Use File.WriteAllText() for one complete string, File.WriteAllLines() for multiple lines, and StreamWriter for incremental or controlled writing. Use append methods when existing content must be preserved, create missing directories before writing, and handle file-system exceptions where recovery is possible.
TutorialKart.com