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)




12 comments:

  1. Thanks for this code.
    it is really useful for me

    ReplyDelete
  2. That was help full

    Thanks

    ReplyDelete
  3. Thats it ! simple

    Thankssssss

    ReplyDelete
  4. This was really lucid and it worked. Thnaks.

    ReplyDelete
  5. wow Excellent..........

    ReplyDelete
  6. Thank you so much for this! :)

    ReplyDelete
  7. Thanks very much for this sample

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

    ReplyDelete
  9. 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

    ReplyDelete