Base64 encode and decode UTF-8 text safely
C#
using System;
using System.Text;
static string ToBase64(string text) => Convert.ToBase64String(Encoding.UTF8.GetBytes(text));
static string FromBase64(string encoded)
{
if (encoded.Length == 0 || encoded.Length % 4 != 0)
throw new FormatException("Base64 length must be a non-zero multiple of 4.");
try
{
return Encoding.UTF8.GetString(Convert.FromBase64String(encoded));
}
catch (FormatException ex)
{
throw new FormatException($"Invalid Base64: {ex.Message}", ex);
}
}