Convert String to Base64 and Base64 to String

System.Text.Encoding class provides methods to convert String to Base64 and vice-versa.

Convert String to Base64

First convert the string to a byte array and then use the Convert.ToBase64String() method to convert the byte array to a Base64 string.

C#


    byte[] byt = System.Text.Encoding.UTF8.GetBytes(strOriginal);

    // convert the byte array to a Base64 string

    strModified = Convert.ToBase64String(byt);



VB.NET


    Dim byt As Byte() = System.Text.Encoding.UTF8.GetBytes(strOriginal)

    ' convert the byte array to a Base64 string

    strModified = Convert.ToBase64String(byt)




Convert Base64 string to String

In order to convert a Base64 string back to the original string, use FromBase64String(). First FromBase64String() converts the string to a byte array and then use the relevant Encoding method to convert the byte array to a string, in our case UTF8.GetString();

C#


    byte[] b = Convert.FromBase64String(strModified);

    strOriginal = System.Text.Encoding.UTF8.GetString(b);



VB.NET


    Dim b As Byte() = Convert.FromBase64String(strModified)

    strOriginal = System.Text.Encoding.UTF8.GetString(b)






Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

11 comments:

Anonymous said...

Thanks for this code.
it is really useful for me

Anonymous said...

That was help full

Thanks

Illutionist said...

Thats it ! simple

Thankssssss

Anonymous said...

This was really lucid and it worked. Thnaks.

Anonymous said...

wow Excellent..........

Anonymous said...

Thank you so much for this! :)

Nipesh Shah said...

Time Saving Code

Thanks

Anonymous said...

thank you!!!

Anonymous said...

Thanks

Anonymous said...

Thanks very much for this sample

buyi wen said...

I'm not a developer, i always use the free online base64 string converter to encode and decode base64.