Convert string to base64 string

A while back I came across the need to convert regular string text into a base64 string. .Net makes this fairly easy to do. I created a public static class and added two public static methods to encode/decode strings. Now they don't have to be static or public but I tend to make helper/utility classes that way. All of the classes being used are in the System and System.Text namespaces.


/// <summary>
/// Encodes the string to Base64.
/// </summary>
/// <param name="valueToEndcode">The value to endcode.</param>
/// <returns>A base64 encoded string.</returns>
public static string EncodeStringToBase64( string valueToEndcode )
{
// encode the string into ascii byte array
byte[] toEncodeAsBytes = ASCIIEncoding.ASCII.GetBytes( valueToEndcode );

// use the byte array to encode to a base64 string
string returnValue = Convert.ToBase64String( toEncodeAsBytes );

// drop back the new encoded string value
return returnValue;

}

/// <summary>
/// Decodes the string from Base64.
/// </summary>
/// <param name="encodedData">The encoded data.</param>
/// <returns>An Ascii encoded string.</returns>
static public string DecodeStringFromBase64( string encodedData )
{
// get a byte array from the encoded data
byte[] encodedDataAsBytes = Convert.FromBase64String( encodedData );

// turn the byte array into ascii data
string returnValue = ASCIIEncoding.ASCII.GetString( encodedDataAsBytes );

// drop back the new decoded string
return returnValue;
}



Now for my situation I only need to worry about ascii encoded strings. If you're worried about needing a different encoding it would be trivial to swap out the ASCIIEncoding class for a different encoding class or to simply pass the desired encoding into the functions themselves.

Comments

Popular posts from this blog

String.Replace vs Regex.Replace

C# Form Application in Kiosk Mode/Fullscreen

C# using a transaction with ODBC