How to easily encode and decode a string in Base64 format

Hi

Yesterday I had a task where I had to encode some string in the Base64 format and then later decode the same back to string. When I first started looking at the System.Convert class, I found the convert to base64 function does not take any string parameter.

You can still convert a string into base64 format in one line of code. The code to convert a string to base64 format is

string str64;
string str64back;
string str="Vikram"; 

            str64 = Convert.ToBase64String(System.Text.Encoding.Unicode.GetBytes(str));

            str64back = Text.Encoding.Unicode.GetString(Convert.FromBase64String(str64));

Here I am taking 3 string variable. The variable string is the variable to bhe converted. I first convert the variable to a base64Encoded string(str64) and then convert the base64 string back to simple string that we started with.

Hope this helps
Thanks
Vikram


Share this post   Email it

Feedback

Posted on 3/28/2007 12:49:36 AM

hi there Vikram,

In this code you used Encoding.Unicode to get the bytes.
I tried to use Encoding.ASCII and UTF8, both gives the same result (ASCII and UTF8). Only Unicode gives different result.

Take a look here

? convert.ToBase64String( system.Text.Encoding.ASCII.GetBytes( "test string here" ) )
"dGVzdCBzdHJpbmcgaGVyZQ=="

? convert.ToBase64String( system.Text.Encoding.utf8.GetBytes( "test string here" ) )
"dGVzdCBzdHJpbmcgaGVyZQ=="

? convert.ToBase64String( system.Text.Encoding.unicode.GetBytes( "test string here" ) )
"dABlAHMAdAAgAHMAdAByAGkAbgBnACAAaABlAHIAZQA="

Can you give me an explanation for this ?

Thanks and kind regards,

SHC

p.s. I hope you can email me if you any answer :)

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 

Copyright © 2006 - 2010 Vikram Lakhotia