Press "Enter" to skip to content

How to encode and decode a Base64 string in C#

Here’s how to encode a string to Base64 in C#, and how to convert a Base64-encoded string back to a normal string.

void Main()
{
	string myString = "This is my test string";
	var base64EncodedString = EncodeToBase64(myString);
	Console.WriteLine($"ENCODED: {base64EncodedString}");
	var decodedString = DecodeFromBase64(base64EncodedString);
	Console.WriteLine($"DECODED: {decodedString}");
}
public static string EncodeToBase64(string text)
{
	// Convert string to byte array
	byte[] textAsBytes = System.Text.Encoding.UTF8.GetBytes(text);
	
	// Convert byte array to Base64 string
	return System.Convert.ToBase64String(textAsBytes);
}
public static string DecodeFromBase64(string encodedText)
{
	// Convert Base64 string to byte array
	byte[] encodedBytes = System.Convert.FromBase64String(encodedText);
	
	// Convert byte array to UTF8 string
	return System.Text.Encoding.UTF8.GetString(encodedBytes);
}

In the example code, the Main function creates the “myString” variable, passes it into the EncodeToBase64 function (getting back a Base64-encoded string), then passes the encoded string into DecodeFromBase64 function (getting back the original string)

In the EncodeToBase64 function, we convert the string to a byte array using the System.Text.Encoding.UTF8.GetBytes function. Then we pass the byte array into the System.Convert.ToBase64String function to get the Base64-encoded string.

In the DecodeFromBase64 function, we pass in a Base64-encoded string and convert it to a byte array by using the System.Convert.FromBase64String function. We pass the byte array into the System.Text.Encoding.UTF8.GetString function to get the normal (UTF8) string.

If we run this code, we see the encoded and decoded values below:

ENCODED: VGhpcyBpcyBteSB0ZXN0IHN0cmluZw==

DECODED: This is my test string

Notice that the Base64-encoded string ends with two equal signs.

So, if you see a string of random looking characters that ends with two equal signs, there’s a good chance it’s a Base64 encoded string, and you would just need to run the decode function to see what the original string.

    Leave a Reply

    Your email address will not be published.

    This site uses Akismet to reduce spam. Learn how your comment data is processed.