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, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

10 Responses to "Convert String to Base64 and Base64 to String"
  1. Anonymous said...
    September 1, 2009 at 12:29 AM

    Thanks for this code.
    it is really useful for me

  2. Anonymous said...
    June 28, 2010 at 7:10 AM

    That was help full

    Thanks

  3. Illutionist said...
    July 9, 2010 at 3:01 AM

    Thats it ! simple

    Thankssssss

  4. Anonymous said...
    November 4, 2010 at 12:37 PM

    This was really lucid and it worked. Thnaks.

  5. Anonymous said...
    December 7, 2011 at 11:29 PM

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

  6. Anonymous said...
    April 12, 2012 at 1:34 AM

    Thank you so much for this! :)

  7. Nipesh Shah said...
    May 1, 2012 at 6:10 AM

    Time Saving Code

    Thanks

  8. Anonymous said...
    May 1, 2012 at 1:45 PM

    thank you!!!

  9. Anonymous said...
    October 3, 2013 at 4:25 AM

    Thanks

  10. Anonymous said...
    October 11, 2013 at 2:07 AM

    Thanks very much for this sample

 

Copyright © 2009-2014 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions