Programming

Encoding Strings to Base64 in C#

steloflute 2012. 6. 14. 01:49

http://arcanecode.com/2007/03/21/encoding-strings-to-base64-in-c/



    static public string EncodeTo64(string toEncode)

    {

      byte[] toEncodeAsBytes

            = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);

      string returnValue

            = System.Convert.ToBase64String(toEncodeAsBytes);

      return returnValue;

    }

 

Note two things, first I am using ASCII encoding, which should cover most folks. Just in case though, System.Text has encodings for the various flavors of UTF as well as Unicode. Just choose the appropriate encoding method for your need.

Second, I made the class static because I was using a console app for my test harness. While it could be static in your class, there’s no reason it has to be. Your choice.

OK, we’ve got the string encoded, at some point we’re going to want to decode it. We essentially do the reverse of encoding, we call the FromBase64String and pass in our encoded string, which returns a byte array. We then call the AsciiEncoding GetString to convert our byte array to a string. Here’s a small method to Decode your Base64 strings.

    static public string DecodeFrom64(string encodedData)

    {

      byte[] encodedDataAsBytes

          = System.Convert.FromBase64String(encodedData);

      string returnValue =

         System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);

      return returnValue;

    }



To summarize,

 

encode:

var stringEncoded = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(stringData))

 

decode:

var stringData = ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(stringEncoded));

 

 

'Programming' 카테고리의 다른 글

C to Go  (0) 2012.06.15
(.NET) Free .NET decompiler - dotPeek  (0) 2012.06.14
(Haskell) eclipsefp run main function  (0) 2012.06.13
(Book) Real World Haskell  (0) 2012.06.12
(Haskell) Try Haskell in your browser  (0) 2012.06.12