Convert String to Base64 and Base64 to String

The System.Text.Encoding class provides methods to convert string to Base64 and vice versa

String to Base64

The conversion involves two processes:

a. Convert string to a byte array

b. 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)

Base64 string to Original String

In order to convert a Base64 string back to the original string, use FromBase64String(). The conversion involves two processes:

a. The FromBase64String() converts the string to a byte array

b. 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)

Check out some additional String functions over here 30 Common String Operations in C# and VB.NET






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.

No comments: