How do I encode and decode a base64 string?

Encode

public static string Base64Encode(string plainText) {
  var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
  return System.Convert.ToBase64String(plainTextBytes);
}

Decode

public static string Base64Decode(string base64EncodedData) {
  var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
  return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}

One liner code:

Note: Use System and System.Text directives.

Encode:

string encodedStr = Convert.ToBase64String(Encoding.UTF8.GetBytes("inputStr"));

Decode:

string inputStr = Encoding.UTF8.GetString(Convert.FromBase64String(encodedStr));

Tags:

C#

Base64