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



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

0 Responses to "Convert String to Base64 and Base64 to String"
 

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