Tuesday, June 26, 2012

Encode/Decode to Base64


//Encode

static public string EncodeTo64(string toEncode)
    {
      byte[] toEncodeAsBytes
            = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
      string returnValue
            = System.Convert.ToBase64String(toEncodeAsBytes);
      return returnValue;
    }


//Decode

    static public string DecodeFrom64(string encodedData)
    {
      byte[] encodedDataAsBytes
          = System.Convert.FromBase64String(encodedData);
      string returnValue =
         System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);
      return returnValue;
    }


//Usage

      string myData = “Here is a string to encode.”;

      string myDataEncoded = EncodeTo64(myData);
      Console.WriteLine(myDataEncoded);

      string myDataUnencoded = DecodeFrom64(myDataEncoded);
      Console.WriteLine(myDataUnencoded);

      Console.ReadLine();

Link where I got this from:
http://arcanecode.com/2007/03/21/encoding-strings-to-base64-in-c/

No comments:

Post a Comment