Sunday, 2 November 2014

Encode and Decode to Base64 in C#


Base64
Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding.

Base64 encoding schemes are commonly used when there is a need to encode binary data that needs to be stored and transferred over media that are designed to deal with textual data. This is to ensure that the data remains intact without modification during transport. Base64 is commonly used in a number of applications including email via MIME, and storing complex data in XML.

Here is a simple static class that allows you to Encode and Decode a value to and from Base64 encoding!

Code Snippet
  1. public class Base64Helper
  2. {
  3.     public static string Encode(string plainText)
  4.     {
  5.         var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
  6.         return System.Convert.ToBase64String(plainTextBytes);
  7.     }
  8.  
  9.     public static string Decode(string base64EncodedData)
  10.     {
  11.         var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
  12.         return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
  13.     }
  14. }
End of Code Snippet

No comments: