Mastering Base64 Encoding and Decoding in C#

Valentyn Osidach đź“š
.Net Programming
Published in
3 min readJul 15, 2024
.Net Base 64 Image

Understanding Base64 Encoding and Decoding in C# A Comprehensive Guide for Developers

Base64 encoding is a common technique used to convert binary data into a textual format. This is particularly useful for transmitting data over media that are designed to deal with text, such as JSON or XML. In this article, we’ll dive deep into Base64 encoding and decoding in C#, exploring practical applications, benefits, and how to implement it efficiently.

What is Base64 Encoding?

Base64 encoding takes binary data and translates it into a string of ASCII characters. This encoding scheme uses 64 different ASCII characters (A-Z, a-z, 0–9, +, and /) to represent the binary data. The resulting encoded data is typically about 33% larger than the original binary data.

Why Use Base64 Encoding?

  • Text Representation: Base64 allows binary data to be represented as text, making it easier to include binary data in text-based formats like XML, JSON, or URLs.
    - Data Integrity: It ensures that the data remains intact without modification during transport.
    - Compatibility: Base64 is widely used in various protocols such as MIME for email, JSON for APIs, and more.

Encoding and Decoding in C#

Encoding Binary Data to Base64

In C#, the `Convert` class provides a straightforward way to encode binary data to a Base64 string using the `ToBase64String` method.

byte[] binaryData = System.Text.Encoding.UTF8.GetBytes("Hello, World!");
string base64EncodedData = Convert.ToBase64String(binaryData);

Console.WriteLine("Encoded: " + base64EncodedData);

In this example, we convert a simple “Hello, World!” string to a byte array using UTF-8 encoding and then encode it to a Base64 string.

Decoding Base64 to Binary Data

Decoding is just as simple using the `FromBase64String` method of the `Convert` class.

string base64EncodedData = "SGVsbG8sIFdvcmxkIQ==";
byte[] binaryData = Convert.FromBase64String(base64EncodedData);
string decodedString = System.Text.Encoding.UTF8.GetString(binaryData);

Console.WriteLine("Decoded: " + decodedString);

Here, we take a Base64 encoded string, decode it back to binary data, and then convert that binary data back to a readable string using UTF-8 encoding.

Practical Applications

1. Storing Binary Data in JSON

Base64 encoding is particularly useful for storing binary data in JSON. For example, if you need to send an image or file through a JSON-based API, you can encode the file’s binary data to Base64 and include it in the JSON payload.


using Newtonsoft.Json;

byte[] fileData = System.IO.File.ReadAllBytes("path/to/your/image.jpg");
string base64Content = Convert.ToBase64String(fileData);
var file = new FileData
{
FileName = "image.jpg",
Base64Content = base64Content
};
string json = JsonConvert.SerializeObject(file);

Console.WriteLine(json);

public class FileData
{
public string FileName { get; set; }
public string Base64Content { get; set; }
}

2. Including Binary Data in URLs

Base64 encoding can be used to safely include binary data in URLs. However, since `+` and `/` characters can cause issues in URLs, you may need to use a URL-safe Base64 encoding variant.

byte[] binaryData = System.Text.Encoding.UTF8.GetBytes("Hello, World!");
string base64EncodedData = Convert.ToBase64String(binaryData);
string urlSafeBase64EncodedData = base64EncodedData.Replace('+', '-').Replace('/', '_').Replace("=", "");

Console.WriteLine("URL Safe Encoded: " + urlSafeBase64EncodedData);

3. Data Integrity Verification

Base64 encoding is also used in hashing and digital signatures where the integrity of data needs to be verified.

using System.Security.Cryptography;
using System.Text;

string originalData = "Hello, World!";
byte[] originalDataBytes = Encoding.UTF8.GetBytes(originalData);
using var sha256 = SHA256.Create();

byte[] hashBytes = sha256.ComputeHash(originalDataBytes);
string base64Hash = Convert.ToBase64String(hashBytes);

Console.WriteLine("SHA-256 Hash in Base64: " + base64Hash);

Conclusion

Base64 encoding and decoding are fundamental skills in C# programming, enabling the efficient handling and transport of binary data in textual formats. Whether you’re storing binary data in JSON, embedding it in URLs, or ensuring data integrity, Base64 provides a reliable and easy-to-use solution. The `Convert` class in C# makes encoding and decoding a straightforward task, empowering developers to handle binary data with ease.

By understanding and implementing Base64 encoding and decoding, you can enhance your applications’ data handling capabilities, ensuring compatibility, integrity, and ease of transport across various platforms and protocols.

--

--

Valentyn Osidach đź“š
.Net Programming

I am a software developer from Ukraine with more than 7 years of experience. I specialize in C# and .NET and love sharing my development knowledge. 👨🏻‍💻