C# Encoding - Encode and Decode Text
last modified November 15, 2026
This article shows how to encode and decode text in C# with the
System.Text.Encoding class. Understanding how text is turned into
bytes is essential for working with files, network protocols, and data
exchanged with other systems.
Unicode is a universal computing industry standard for the consistent encoding, representation, and handling of text in most of the world's writing systems. It assigns every character a number called a code point, for example U+0041 for the letter A or U+1F418 for the elephant emoji.
In C#, a string is a sequence of UTF-16 code units, represented by the
char type. Characters from the Basic Multilingual Plane, which
covers most living languages, take one code unit. Characters with code points
above U+FFFF, such as most emojis, take two code units called a
surrogate pair.
Encoding is the process of converting a sequence of characters into a sequence of bytes, so that the text can be stored or transmitted. Decoding reverses the process and turns bytes back into characters. Both sides must use the same encoding; otherwise, the text gets corrupted.
.NET provides several built-in encodings through static properties of the
Encoding class: UTF8, Unicode (UTF-16
little endian), BigEndianUnicode, UTF32,
Latin1, and ASCII. UTF-8 is the most common encoding
for files and the web, and it is the default for file and stream APIs in .NET.
UTF-7 is obsolete and should not be used.
In the examples, characters outside of ASCII are written as escape sequences:
\u00E9 for a character with a four-digit code point and
\U0001F418 for one with a larger code point.
C# Encoding GetByteCount
The GetByteCount method returns the number of bytes produced by
encoding the specified characters.
using System.Text;
string text = "one \U0001F418 and three \U0001F40B";
Console.WriteLine($"Length: {text.Length}");
int n = Encoding.UTF8.GetByteCount(text);
Console.WriteLine($"UTF-8: {n}");
n = Encoding.Unicode.GetByteCount(text);
Console.WriteLine($"UTF-16: {n}");
n = Encoding.BigEndianUnicode.GetByteCount(text);
Console.WriteLine($"UTF-16BE: {n}");
n = Encoding.UTF32.GetByteCount(text);
Console.WriteLine($"UTF-32: {n}");
n = Encoding.Latin1.GetByteCount(text);
Console.WriteLine($"Latin1: {n}");
n = Encoding.ASCII.GetByteCount(text);
Console.WriteLine($"ASCII: {n}");
The example prints the length of a string and the number of bytes which the string takes in different encodings.
string text = "one \U0001F418 and three \U0001F40B";
The string has 15 ASCII characters and two emojis. Each emoji is a surrogate
pair, so the Length property is 19.
int n = Encoding.UTF8.GetByteCount(text);
UTF-8 is a variable-length encoding. ASCII characters take one byte, and characters above U+FFFF take four bytes: 15 + 2 * 4 = 23 bytes.
n = Encoding.Unicode.GetByteCount(text);
In UTF-16, each code unit takes two bytes: 19 * 2 = 38 bytes. UTF-32 uses four bytes for every code point; there are 17 code points, which gives 68 bytes.
n = Encoding.Latin1.GetByteCount(text);
Latin1 and ASCII are single-byte encodings and cannot represent emojis. Each code unit of a surrogate pair is replaced with one question mark, so the count equals the string length.
$ dotnet run Length: 19 UTF-8: 23 UTF-16: 38 UTF-16BE: 38 UTF-32: 68 Latin1: 19 ASCII: 19
C# Encoding GetBytes
The GetBytes method returns a byte array containing the results of
encoding the specified characters.
using System.Text;
string text = "one \U0001F418 and three \U0001F40B";
Console.WriteLine("UTF-8 bytes");
byte[] utf8Data = Encoding.UTF8.GetBytes(text);
ShowBytes(utf8Data);
Console.WriteLine("UTF-16 bytes");
byte[] utf16Data = Encoding.Unicode.GetBytes(text);
ShowBytes(utf16Data);
Console.WriteLine("UTF-16BE bytes");
byte[] utf16BEData = Encoding.BigEndianUnicode.GetBytes(text);
ShowBytes(utf16BEData);
Console.WriteLine("Latin1 bytes");
byte[] latin1Data = Encoding.Latin1.GetBytes(text);
ShowBytes(latin1Data);
void ShowBytes(byte[] data)
{
foreach (var chunk in data.Chunk(16))
{
Console.WriteLine(string.Join(" ", chunk.Select(b => b.ToString("X2"))));
}
}
The example encodes the string with four encodings and prints the bytes in hexadecimal format.
void ShowBytes(byte[] data)
{
foreach (var chunk in data.Chunk(16))
{
Console.WriteLine(string.Join(" ", chunk.Select(b => b.ToString("X2"))));
}
}
The local function prints the bytes in rows of sixteen. The X2
format specifier writes a byte as two hexadecimal digits.
In the output, the elephant emoji is F0 9F 90 98 in UTF-8. In
UTF-16, it is the surrogate pair D83D DC18; the little-endian form stores the
low byte of each code unit first (3D D8 18 DC), the big-endian
form the high byte first (D8 3D DC 18). Latin1 replaces each half
of the surrogate pair with 3F, which is the question mark.
$ dotnet run UTF-8 bytes 6F 6E 65 20 F0 9F 90 98 20 61 6E 64 20 74 68 72 65 65 20 F0 9F 90 8B UTF-16 bytes 6F 00 6E 00 65 00 20 00 3D D8 18 DC 20 00 61 00 6E 00 64 00 20 00 74 00 68 00 72 00 65 00 65 00 20 00 3D D8 0B DC UTF-16BE bytes 00 6F 00 6E 00 65 00 20 D8 3D DC 18 00 20 00 61 00 6E 00 64 00 20 00 74 00 68 00 72 00 65 00 65 00 20 D8 3D DC 0B Latin1 bytes 6F 6E 65 20 3F 3F 20 61 6E 64 20 74 68 72 65 65 20 3F 3F
C# Encoding GetString
The GetString method builds a string by decoding a sequence of
bytes.
using System.Text; string text = "one \U0001F418 and three \U0001F40B"; byte[] utf8Data = Encoding.UTF8.GetBytes(text); Console.WriteLine(Encoding.UTF8.GetString(utf8Data)); byte[] utf16Data = Encoding.Unicode.GetBytes(text); Console.WriteLine(Encoding.Unicode.GetString(utf16Data)); byte[] latin1Data = Encoding.Latin1.GetBytes(text); Console.WriteLine(Encoding.Latin1.GetString(latin1Data));
We encode the string into bytes with GetBytes and decode the
bytes back with GetString, using the same encoding on both
sides.
byte[] latin1Data = Encoding.Latin1.GetBytes(text); Console.WriteLine(Encoding.Latin1.GetString(latin1Data));
UTF-8 and UTF-16 preserve the original text. Latin1 cannot represent the emojis; they were replaced with question marks during encoding, and decoding cannot bring them back.
$ dotnet run one 🐘 and three 🐋 one 🐘 and three 🐋 one ?? and three ??
Decoding with a wrong encoding
When bytes are decoded with a different encoding than the one used to produce them, we get garbled text, sometimes called mojibake.
using System.Text; string word = "na\u00EFve caf\u00E9"; byte[] data = Encoding.UTF8.GetBytes(word); Console.WriteLine(Encoding.UTF8.GetString(data)); Console.WriteLine(Encoding.Latin1.GetString(data)); Console.WriteLine(Encoding.ASCII.GetString(data)); byte[] latin1 = Encoding.Latin1.GetBytes(word); Console.WriteLine(Encoding.UTF8.GetString(latin1));
We encode a string with accented characters in UTF-8 and decode it with several encodings.
Console.WriteLine(Encoding.Latin1.GetString(data));
The letter ï is encoded in UTF-8 as two bytes,
C3 AF. Latin1 decodes each byte as a separate character, giving
ï.
Console.WriteLine(Encoding.ASCII.GetString(data));
ASCII only covers bytes 0 to 127. Every byte above that is decoded as a question mark.
byte[] latin1 = Encoding.Latin1.GetBytes(word); Console.WriteLine(Encoding.UTF8.GetString(latin1));
In Latin1, the accented letters take a single byte. Such a byte is not a valid UTF-8 sequence, and the UTF-8 decoder replaces it with the replacement character U+FFFD.
$ dotnet run naïve café naïve café na??ve caf?? na�ve caf�
Encoding errors
By default, encoders silently replace characters they cannot represent, and decoders replace invalid bytes. When data loss must not go unnoticed, we can create an encoding which throws an exception instead.
using System.Text;
var ascii = Encoding.GetEncoding("us-ascii",
EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback);
try
{
byte[] data = ascii.GetBytes("caf\u00E9");
}
catch (EncoderFallbackException e)
{
Console.WriteLine(e.Message);
}
var strictUtf8 = new UTF8Encoding(false, true);
byte[] bad = [0x63, 0x61, 0x66, 0xE9];
try
{
string s = strictUtf8.GetString(bad);
}
catch (DecoderFallbackException e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine(Encoding.UTF8.GetString(bad));
The example creates a strict ASCII encoding and a strict UTF-8 encoding.
var ascii = Encoding.GetEncoding("us-ascii",
EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback);
The GetEncoding method accepts an encoder fallback and a decoder
fallback. With the exception fallbacks, an unencodable character throws an
EncoderFallbackException.
var strictUtf8 = new UTF8Encoding(false, true);
The first parameter of the UTF8Encoding constructor controls the
byte order mark, the second makes the decoder throw a
DecoderFallbackException on invalid bytes.
Console.WriteLine(Encoding.UTF8.GetString(bad));
The default Encoding.UTF8 instance decodes the same bytes without
an error and inserts the replacement character.
$ dotnet run Unable to translate Unicode character \\u00E9 at index 3 to specified code page. Unable to translate bytes [E9] at index 3 from specified code page to Unicode. caf�
C# Encoding.Convert
The Encoding.Convert method converts a byte array from one
encoding to another.
using System.Text;
string text = "one \U0001F418 and three \U0001F40B";
byte[] utf16Data = Encoding.Unicode.GetBytes(text);
byte[] utf8Data = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, utf16Data);
Console.WriteLine($"UTF-16: {utf16Data.Length} bytes");
Console.WriteLine($"UTF-8: {utf8Data.Length} bytes");
string output = Encoding.UTF8.GetString(utf8Data);
Console.WriteLine(output);
In this example, we convert UTF-16 bytes to UTF-8 bytes.
byte[] utf8Data = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, utf16Data);
The method decodes the bytes with the first encoding and encodes the characters with the second. This is useful when data received in one encoding must be passed on in another. For our text, the UTF-8 form is 15 bytes shorter.
$ dotnet run UTF-16: 38 bytes UTF-8: 23 bytes one 🐘 and three 🐋
Code page encodings
Older systems often store text in single-byte code pages, such as Windows-1250
for Central European languages. On .NET Core and .NET 5 and later, these code
pages are not available by default. We must register the
CodePagesEncodingProvider first; otherwise,
GetEncoding throws an ArgumentException saying that
'windows-1250' is not a supported encoding name.
using System.Text;
string text = "Dobr\u00FD de\u0148";
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Encoding cp1250 = Encoding.GetEncoding("windows-1250");
Console.WriteLine($"{cp1250.EncodingName}, code page {cp1250.CodePage}");
byte[] data = cp1250.GetBytes(text);
Console.WriteLine(Convert.ToHexString(data));
Console.WriteLine(cp1250.GetString(data));
File.WriteAllText("cp1250.txt", text, cp1250);
string content = File.ReadAllText("cp1250.txt", cp1250);
Console.WriteLine(content);
The example encodes Slovak text in the Windows-1250 code page.
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
The provider is part of .NET; no extra package is needed. It is registered once at the start of the program.
Encoding cp1250 = Encoding.GetEncoding("windows-1250");
We get the encoding by its name. The code page number,
GetEncoding(1250), works as well.
byte[] data = cp1250.GetBytes(text); Console.WriteLine(Convert.ToHexString(data));
Every character takes exactly one byte; the letter ň is
F2 in this code page. Convert.ToHexString prints the
bytes as a hexadecimal string.
File.WriteAllText("cp1250.txt", text, cp1250);
string content = File.ReadAllText("cp1250.txt", cp1250);
The file helper methods take an encoding parameter too.
$ dotnet run Central European (Windows), code page 1250 446F6272FD206465F2 Dobrý deň Dobrý deň
Byte order mark
A byte order mark (BOM) is a short byte sequence at the start of a file that
identifies its encoding. The GetPreamble method returns the BOM
of an encoding.
using System.Text;
string text = "one \U0001F418 and three \U0001F40B";
File.WriteAllText("data1.txt", text);
File.WriteAllText("data2.txt", text, Encoding.UTF8);
File.WriteAllText("data3.txt", text, Encoding.Unicode);
foreach (var fileName in new[] { "data1.txt", "data2.txt", "data3.txt" })
{
byte[] data = File.ReadAllBytes(fileName);
string start = Convert.ToHexString(data, 0, 4);
Console.WriteLine($"{fileName}: {data.Length} bytes, starts with {start}");
}
Console.WriteLine(Convert.ToHexString(Encoding.UTF8.GetPreamble()));
Console.WriteLine(Convert.ToHexString(Encoding.Unicode.GetPreamble()));
Console.WriteLine(new UTF8Encoding(false).GetPreamble().Length);
We write the same text into three files and look at their first bytes.
File.WriteAllText("data1.txt", text);
Without an encoding argument, File.WriteAllText writes UTF-8
without a BOM.
File.WriteAllText("data2.txt", text, Encoding.UTF8);
The Encoding.UTF8 instance has a preamble, so the file starts
with the three bytes EF BB BF.
File.WriteAllText("data3.txt", text, Encoding.Unicode);
The UTF-16 little-endian BOM is FF FE.
Console.WriteLine(new UTF8Encoding(false).GetPreamble().Length);
To write UTF-8 without a BOM explicitly, we create a
UTF8Encoding object and pass false to its
constructor.
$ dotnet run data1.txt: 23 bytes, starts with 6F6E6520 data2.txt: 26 bytes, starts with EFBBBF6F data3.txt: 40 bytes, starts with FFFE6F00 EFBBBF FFFE 0
C# read/write data with Encoding
StreamWriter and StreamReader take an encoding as a
constructor parameter. When reading, the BOM takes precedence over the given
encoding unless BOM detection is turned off.
using System.Text;
string text = "one \U0001F418 and three \U0001F40B";
using (var sw = new StreamWriter("data.txt", false, Encoding.Unicode))
{
sw.WriteLine(text);
}
using (var sr = new StreamReader("data.txt", Encoding.Unicode))
{
Console.WriteLine(sr.ReadLine());
}
using (var sr = new StreamReader("data.txt", Encoding.UTF8))
{
Console.WriteLine(sr.ReadLine());
Console.WriteLine(sr.CurrentEncoding.EncodingName);
}
using (var sr = new StreamReader("data.txt", Encoding.UTF8, false))
{
string? line = sr.ReadLine();
Console.WriteLine(line?[..12].Replace('\0', '.'));
}
We write a line in UTF-16 and read it back in three ways.
using (var sw = new StreamWriter("data.txt", false, Encoding.Unicode))
The second parameter of the constructor tells whether to append to the file, the third one specifies the encoding. The writer starts the file with the UTF-16 BOM.
using (var sr = new StreamReader("data.txt", Encoding.UTF8))
{
Console.WriteLine(sr.ReadLine());
Console.WriteLine(sr.CurrentEncoding.EncodingName);
}
Even though we pass UTF-8, the reader detects the UTF-16 BOM and switches to
UTF-16. The CurrentEncoding property confirms it.
using (var sr = new StreamReader("data.txt", Encoding.UTF8, false))
The third parameter turns BOM detection off. The UTF-16 bytes are now decoded as UTF-8 and the result is garbage: the BOM bytes become replacement characters and every zero byte becomes a NUL character, which we print as a dot.
$ dotnet run one 🐘 and three 🐋 one 🐘 and three 🐋 Unicode ��o.n.e. .=�
Code units, runes, and text elements
The length of a string is the number of UTF-16 code units, which is not always
the number of characters a user sees. The Rune type represents a
Unicode code point, and StringInfo counts text elements
(grapheme clusters).
using System.Globalization;
using System.Text;
string text = "caf\u00E9 \U0001F418 \U0001F44D\U0001F3FD";
Console.WriteLine($"UTF-16 code units: {text.Length}");
Console.WriteLine($"Runes: {text.EnumerateRunes().Count()}");
Console.WriteLine($"Text elements: {new StringInfo(text).LengthInTextElements}");
Console.WriteLine($"UTF-8 bytes: {Encoding.UTF8.GetByteCount(text)}");
foreach (Rune rune in text.EnumerateRunes())
{
Console.Write($"U+{rune.Value:X4} ");
}
Console.WriteLine();
The example measures a string with an accented letter and two emojis in four ways.
string text = "caf\u00E9 \U0001F418 \U0001F44D\U0001F3FD";
The last emoji is a thumbs up followed by a skin tone modifier. Together they display as one symbol.
Console.WriteLine($"Runes: {text.EnumerateRunes().Count()}");
The EnumerateRunes method returns the code points of the string.
Each emoji is one rune but two code units.
Console.WriteLine($"Text elements: {new StringInfo(text).LengthInTextElements}");
The thumbs up and its modifier form a single text element, so there are eight text elements but nine runes.
$ dotnet run UTF-16 code units: 12 Runes: 9 Text elements: 8 UTF-8 bytes: 19 U+0063 U+0061 U+0066 U+00E9 U+0020 U+1F418 U+0020 U+1F44D U+1F3FD
C# Base64 encoding and decoding
Base64 is not a character encoding but a binary-to-text encoding. It
represents arbitrary bytes with 64 printable ASCII characters, so binary data
can be embedded in text formats such as JSON, XML, or email. The
Convert.ToBase64String and Convert.FromBase64String
methods encode and decode Base64.
using System.Buffers.Text;
using System.Text;
string text = "Encode this string to Base64!";
byte[] bytes = Encoding.UTF8.GetBytes(text);
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine($"Base64: {base64}");
byte[] decodedBytes = Convert.FromBase64String(base64);
string decodedText = Encoding.UTF8.GetString(decodedBytes);
Console.WriteLine($"Decoded: {decodedText}");
byte[] data = [0xFB, 0xFF, 0xBF, 0x01];
Console.WriteLine(Convert.ToBase64String(data));
Console.WriteLine(Base64Url.EncodeToString(data));
The example encodes a string to Base64, decodes it back, and compares standard Base64 with its URL-safe variant.
byte[] bytes = Encoding.UTF8.GetBytes(text); string base64 = Convert.ToBase64String(bytes);
Base64 works with bytes, so we encode the text to UTF-8 first.
byte[] decodedBytes = Convert.FromBase64String(base64); string decodedText = Encoding.UTF8.GetString(decodedBytes);
Decoding goes in the opposite direction: from Base64 to bytes and from bytes to text.
Console.WriteLine(Base64Url.EncodeToString(data));
Standard Base64 uses the + and / characters and
= padding, which have special meanings in URLs. The
Base64Url class, available since .NET 9, uses - and
_ instead and omits the padding.
$ dotnet run Base64: RW5jb2RlIHRoaXMgc3RyaW5nIHRvIEJhc2U2NCE= Decoded: Encode this string to Base64! +/+/AQ== -_-_AQ
Source
Encoding class - .NET API
Character encoding in .NET
How to use character encoding classes in .NET
In this article we have encoded and decoded text in C#. We have counted and inspected bytes in several encodings, handled encoding errors, used code pages and byte order marks, and worked with runes and Base64. See also the C# StreamReader, C# StreamWriter, and C# string articles.
Author
List all C# tutorials.