uses Extension Methods for Encoding class. The rationale is that someone may need to support different types of encodings (not only UTF8).
Another improvement is failing gracefully with the null results for null entry - it's very useful in real-life scenarios and supports equivalence for X=decode(encode(X)).
Remark: Remember that to use Extension Method you have to (!) import the namespace using keyword (in this case using MyApplication.Helpers.Encoding).
Code:
namespace MyApplication.Helpers.Encoding
{
public static class EncodingForBase64
{
public static string EncodeBase64(this System.Text.Encoding encoding, string text)
{
if (text == null)
{
return null;
}
byte[] textAsBytes = encoding.GetBytes(text);
return System.Convert.ToBase64String(textAsBytes);
}
public static string DecodeBase64(this System.Text.Encoding encoding, string encodedText)
{
if (encodedText == null)
{
return null;
}
byte[] textAsBytes = System.Convert.FromBase64String(encodedText);
return encoding.GetString(textAsBytes);
}
}
}