Convert to and from Base64-encoding in .NET

Code snippet demonstrating how to convert a string value to and from Base64 encoding in .NET.

  • 19 October 2010
  • 0

Base64 encoding is used in various places in .NET and ASP.NET, for example to embed a page’s (dreaded) ViewState in markup.

The following code snippet shows how to convert a string to and from Base64 encoding using C#:

var myString = "This will be converted to Base64";
 
// Convert to Base64
var base64EncodedString = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(myString));
 
// Convert back from Base64
var originalString = ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(base64EncodedString));