5 Oct 2007

Encoding and Decoding Base64 strings

C# example to base-64 encode and decode a string:

using System;
using System.Text;

namespace IFXplus
{
    public static class Base64Utils
    {
        public static string Encode(string data)
        {
            byte[] encData_byte = Encoding.UTF8.GetBytes(data);
            return Convert.ToBase64String(encData_byte);           
        }

        public static string Decode(string data)
        {
            UTF8Encoding encoder = new UTF8Encoding();
            Decoder utf8Decode = encoder.GetDecoder();
            byte[] todecode_byte = Convert.FromBase64String(data);
            int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
            char[] decoded_char = new char[charCount];
            utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
            return new String(decoded_char);
        }
    }
}

See also:

The System.Convert class includes some helper methods to encode/decode base64 strings:

HTH

Currently rated 3.7 by 3 people

  • Currently 3.666667/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Related posts

Comments

trackback

DotNetKicks.com

October 5 2007 12:39

Trackback from DotNetKicks.com

Encoding and Decoding Base64 strings

Add comment


(Will show your Gravatar icon)  

  Country flag





Live preview

Gravatar

May 16 2008 14:58