Here are the examples to encode the plain text to Base64 and decode the plain text from Base64 using C#.
This method is used to Encode plain text to Base64 string.
//Encode Plain Text To Base64 String
public static string ToBase64Encode(string text)
{
if (String.IsNullOrEmpty(text)) {
return text;
}
byte[] textBytes = System.Text.Encoding.UTF8.GetBytes(text);
return Convert.ToBase64String(textBytes);
}
This method is used to decode plain text from a Base64 string.
//Decode Plain Text From Base64 String
public static string ToBase64Decode(string base64EncodedText)
{
if (String.IsNullOrEmpty(base64EncodedText)) {
return base64EncodedText;
}
byte[] base64EncodedBytes = Convert.FromBase64String(base64EncodedText);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
using System;
namespace Program
{
public class Program
{
//Encode Plain Text To Base64 String
public static string ToBase64Encode(string text)
{
if (String.IsNullOrEmpty(text))
{
return text;
}
byte[] textBytes = System.Text.Encoding.UTF8.GetBytes(text);
return Convert.ToBase64String(textBytes);
}
//Decode Plain Text From Base64 String
public static string ToBase64Decode(string base64EncodedText)
{
if (String.IsNullOrEmpty(base64EncodedText))
{
return base64EncodedText;
}
byte[] base64EncodedBytes = Convert.FromBase64String(base64EncodedText);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
public static void Main()
{
string str = "Hello, TutorialsRack!";
string encodedText = ToBase64Encode(str);
Console.WriteLine("Base64 Encoded String: " + encodedText);
string decodedText = ToBase64Decode(encodedText);
Console.WriteLine("Base64 Decoded String: " + decodedText);
Console.ReadLine();
}
}
}
Base64 Encoded String: SGVsbG8sIFR1dG9yaWFsc1JhY2sh
Base64 Decoded String: Hello, TutorialsRack!
I hope this article will help you to understand how to encode and decode strings with base64 in C#.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments