In C#, Convert.ToBase64String turns a byte[] into a Base64 string—text that uses A–Z, a–z, 0–9, +, /, and = padding.
Use it when you need to store binary data in JSON, XML, or other text channels. Decode later with FromBase64String.
This is a static member of System.Convert. You call it with the type name, such as Convert.ToBase64String(...). Convert is the everyday API for converting between common CLR types in C#.
Syntax
Pass the bytes (and optionally offset/length or Base64FormattingOptions).
Empty arrays produce an empty string. Pair with FromBase64String to round-trip.
Library declarations
C#
public static string ToBase64String(byte[] inArray);
public static string ToBase64String(byte[] inArray, int offset, int length);
Parameters
Parameter
Description
inArray
Required. Bytes to encode.
offset / length
Optional. Slice of the array to encode.
Return Value
Return Value
Description
string
Base64 text.
C# Examples
Example 1 — Three Bytes to Base64
Encode a tiny byte array and print the text.
C#
using System;
class Program {
static void Main() {
byte[] data = { 1, 2, 3 };
string b64 = Convert.ToBase64String(data);
Console.WriteLine(b64);
}
}
Output
AQID
How It Works
Tiny payload. Bytes 1, 2, 3 keep the demo clear.
ToBase64String. Builds the Base64 text.
AQID. Classic short encoding of those three bytes.
Ready to store. The string can travel in JSON or logs.
Example 2 — Encode UTF-8 Text
Convert a string to UTF-8 bytes, then Base64.
C#
using System;
using System.Text;
class Program {
static void Main() {
byte[] data = Encoding.UTF8.GetBytes("Hi");
Console.WriteLine(Convert.ToBase64String(data));
}
}
Output
SGk=
How It Works
UTF-8 bytes. "Hi" becomes two bytes.
Encode. ToBase64String wraps them as text.
Padding =. Base64 may end with equals signs.
Round-trip later. FromBase64String restores the bytes.
Example 3 — Encode Part of an Array
Use offset and length to encode a prefix.
C#
using System;
class Program {
static void Main() {
byte[] data = { 10, 20, 30, 40 };
string all = Convert.ToBase64String(data);
string head = Convert.ToBase64String(data, 0, 2);
Console.WriteLine(all);
Console.WriteLine(head);
}
}
Output
ChQeKA==
ChQ=
How It Works
Full array. First call encodes every byte.
Prefix only. Offset 0, length 2 encodes 10 and 20.
Different text. Shorter input → shorter Base64.
No copy needed. Slice overloads avoid allocating a subarray.
Frequently Asked Questions
No—it is a reversible encoding. Do not treat it as a secret.