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, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

12 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.

Karp BOT said...

THANK YOU SO MUCH ! YOU ARE THE BEST ! I CAN'T SHOW YOU HOW I'M HAPPY :D, AGAIN : THANK YOU SO MUCH, AND AGAIN : THANK YOU SO MUCH MY FRIEND, YOU ARE AWESOME ;DDDDDDDDDD