Back to Home

Write Special Characters to a File in C#

If you need to write special characters such as <, >, &, quotes, or apostrophes to a file, the main point is that plain text files store them as-is. Escaping is mostly relevant when you are writing C# source code or markup, not when the characters are already part of the string value.

Write literal symbols to a file

C# Example Code
string text = "<tag attr=\"value\">Hello & goodbye</tag>";
File.WriteAllText("sample.txt", text);

The file will contain the literal characters exactly as written.

Append with StreamWriter

C# Example Code
using StreamWriter writer = new("sample.txt", append: true);
writer.WriteLine("Use single quotes ' and double quotes \" when needed.");

FAQ

Do I need to escape characters for a text file?

No. Text files store them directly. Escaping matters more in C# string literals and markup languages.

Which API should I choose?

Use File.WriteAllText for a single write and StreamWriter if you need incremental or repeated writes.

Take It Further

C# 12 and .NET 8 book cover

The most comprehensive book covering C# 12 and .NET 8 from scratch to production.

C# 12 and .NET 8 — Modern Cross-Platform Development · Mark J. Price

Get it on Amazon →

As an Amazon Associate I earn from qualifying purchases.