Here we will learn what is base64 encoding, how to encode a string to base64 format in c# with examples, and how to decode base64 encoded string back to the original string in c# with examples.
The base64 is a binary-to-text encoding format that is useful to represent the binary data in an ASCII string format. The base64 character set will consist of alphabets, numbers, and two special characters (+, /). The padding character = may be added to the end of the encoded data to ensure that the length of the encoded string is a multiple of four.
The base64 format is useful to convert the binary data to ASCII string format and that can be easily transmitted across the systems as a text stream. Each base64 character represents 6 bits of binary data so to convert binary data to base64 format, first it will split the binary data into 6-bit chunks.
If you want to send images or documents across multiple systems, it is always advisable to convert that binary data to base64 encoded string format so that you will not face any data loss problems.
Following is the example of converting the string to a base64 encoded string.
If you observe the above code, we are converting the given string to byte arrays using System.Text.Encoding.UTF8.GetBytes method. After that, we used System.Convert.ToBase64String method to convert the byte arrays to base64 encoded string.
When we execute the above c# example, we will get the result below.
Now, we will learn how to decode the encoded base64 string to plain text or original string in c# with examples.
Following is the example of decoding the base64 encoded string to the original string/plain text.
If you observe the above code, we used System.Convert.FromBase64String method to convert the base64 encoded string to byte array. After that, we used System.Text.Encoding.UTF8.GetString method to convert the byte array to the original string.
When we execute the above c# example, we will get the result below.
This is how we can encode and decode the string to base64 format in c# using ToBase64String
and FromBase64String
methods of System.Convert
class based on our requirements.