Base64 Encoding and Decoding in C#
In this post, we’ll discuss Base64 Encoding and Decoding in C#.
Base64 is a group of similar binary-to-text encoding schemes representing binary data in an ASCII string format by translating it into a radix-64 representation. Each Base64 digit represents exactly 6-bits of data that means 4 6-bit Base64 digits can represent 3 bytes.
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 remain intact without modification during transport. Base64 is commonly used in a number of applications, including email via MIME and storing complex data in XML.
C# provides support for Base64 Encoding and Decoding capabilities in System.Convert utility class, which consists of static methods for obtaining instances of encoders (Base64.Encoder) and decoders (Base64.Decoder) for the Base64 encoding scheme.
The following program uses the Convert.ToBase64String() method for encoding the specified byte array into a Base64 encoded string and Convert.FromBase64String() method for decoding back the Base64 encoded string into a newly allocated byte array.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
using System; public class Example { public static string ToBase64Encode(string text) { if (String.IsNullOrEmpty(text)) { return text; } byte[] textBytes = Text.Encoding.UTF8.GetBytes(text); return Convert.ToBase64String(textBytes); } public static string ToBase64Decode(string base64EncodedText) { if (String.IsNullOrEmpty(base64EncodedText)) { return base64EncodedText; } byte[] base64EncodedBytes = Convert.FromBase64String(base64EncodedText); return Text.Encoding.UTF8.GetString(base64EncodedBytes); } public static void Main() { string str = "Hello#World!!"; string encodedText = ToBase64Encode(str); Console.WriteLine("Base64 Encoded String: " + encodedText); string decodedText = ToBase64Decode(encodedText); Console.WriteLine("Base64 Decoded String: " + decodedText); } } /* Output: Base64 Encoded String: SGVsbG8jV29ybGQhIQ== Base64 Decoded String: Hello#World!! */ |
That’s all about base64 encoding and decoding in C#.
Also See:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)