Here is an quick example how to encode/decode a string to base64. This example works already on .net core 2.0 or above.
There are two functions, one to encode and the another to decode a string. It uses the Convert class from System and the encoding from the encoding functions from System.Text, so don’t forget to add the usings in the top of the file.
/// <summary>
/// Encodes a string to base64, using default encoding.
/// </summary>
/// <param name="str">String to encode.</param>
/// <returns>Encdoded string.</returns>
public static string Base64Encode(string str)
{
return Convert.ToBase64String(Encoding.Default.GetBytes(str));
}
/// <summary>
/// Decodes a string from base64, using default encoding.
/// </summary>
/// <param name="str">base64 encoded string.</param>
/// <returns>Decoded string.</returns>
public static string Base64Decode(string str)
{
return Encoding.Default.GetString(Convert.FromBase64String(str));
}
Leave a Reply