C# Base64 Tutorial – Complete Guide

Stepping into the world of programming, we often encounter different data formats and ways to handle them. One such format that comes up often in our coding journeys, especially when dealing with web development or data transmission, is base64. Covering the topic of converting data to base64 in C# today, we’ll dive deep into the ‘what’, ‘why’ and ‘how’.

What is Base64 Encoding and Decoding?

Base64 is a group of binary-to-text encoding schemes that represent binary data, such as an image or file, in an ASCII string format. This technique is widely used when there is a need to encode binary information, especially when that information needs to be stored or sent over media designed to handle text.

What is It For?

So why do we need to convert data, specifically binary data, into base64? There are several reasons:

  • Base64 encoding helps to protect the integrity of the data during transportation, ensuring that it doesn’t get corrupted.
  • It ensures that data remains intact without modification during transport.
  • It is especially useful when sending complex data over mediums that only handle text.

Why Should I Learn It?

If you’re interested in web development, network programming, or anything related to data transmission, understanding base64 is essential. It is a critical tool that ensures data integrity and is used universally, making it a valuable skill in your developer toolkit. More importantly, by learning to work with base64 in a versatile language like C#, you empower yourself to handle web and network programming tasks more efficiently.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Converting String to Base64 in C#

Let’s explore how to convert a common string to base64 encoding in C#. This process involves two main steps: first, we’ll have to convert our string to a byte array, and then we’ll transform this byte array into base64.

string originalString = "Hello, Zenva!";
byte[] byteArray = Encoding.UTF8.GetBytes(originalString);
string base64String = Convert.ToBase64String(byteArray);
Console.WriteLine(base64String);

This code will output a string of characters which represent our original string in base64 encoding.

Converting Base64 back to String in C#

Now let’s do the reverse – convert that base64 string back into its original string format. Here, we will convert the base64 string back to a byte array, and then decode it to our original format.

string base64String = "SGVsbG8sIFplbnZhIQ==";
byte[] byteArray = Convert.FromBase64String(base64String);
string originalString = Encoding.UTF8.GetString(byteArray);
Console.WriteLine(originalString);

Running this will output our original string: “Hello, Zenva!”.

Handling Errors during Base64 Decoding

When handling encoding and decoding, it’s essential to know how to handle potential errors, let’s see how we can do that:

try 
{
  string invalidBase64String = "This is not base64!";
  byte[] byteArray = Convert.FromBase64String(invalidBase64String);
} 
catch (FormatException) 
{
  Console.WriteLine("Invalid base64 string.");
}

This code uses exception handling to deal with errors that arise from decoding an invalid base64 string. This specific example will catch a FormatException and output “Invalid base64 string” to the console.

Converting File content to Base64 in C#

Besides text, base64 is commonly used to encode files. Here’s how we can load a file and convert its content into base64:

string filePath = @"C:\temp\file.txt";
byte[] bytes = File.ReadAllBytes(filePath);
string base64File = Convert.ToBase64String(bytes);
Console.WriteLine(base64File);

This will output a base64 representation of the contents of file.txt, located at the specified path.

Handling Images with Base64

Converting images to base64 strings is a common practice, particularly when we need to send them over HTTP(S) or store them in a database. Here’s how you can convert an image to base64:

string imagePath = @"C:\temp\image.jpg";
byte[] imageBytes = File.ReadAllBytes(imagePath);
string base64Image = Convert.ToBase64String(imageBytes);
Console.WriteLine(base64Image);

This will print out a base64 encoded version of your image file that, when decoded, can be displayed as the original image.

Getting an Image back from Base64

When receiving a base64 string for an image, it is just as crucial to know how to convert it back into an image file. Consider the following example:

string base64Image = "..."; // Your base64 string here
byte[] imageBytes = Convert.FromBase64String(base64Image);

using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
{
    Image image = Image.FromStream(ms, true);
    image.Save(@"C:\temp\image.jpg", ImageFormat.Jpeg);
}

This code converts a base64 string back to an image and saves it to the specified path.

Converting Data to Base64 in C#

Converting binary data to base64 is also commonly needed in programming. Here is how you can achieve this:

byte[] data = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04 }; // example data
string base64Data = Convert.ToBase64String(data);
Console.WriteLine(base64Data);

This code outputs a base64 representation of binary data.

Base64 Conversion: Real-Life Applications

Now that we’ve covered the basics and delved into examples, let’s look at a real-life use case to better understand the importance of base64 encoding and decoding.

Suppose we’re building a web service that handles file uploads. Instead of expecting users to upload files directly, we can ask them to upload base64 encoded versions of those files. This approach can help ensure that files aren’t corrupted during the upload process. The service can then decode these strings back into their original formats.

[HttpPost("upload")]
public IActionResult UploadFile([FromBody] string base64File)
{
  byte[] fileBytes = Convert.FromBase64String(base64File);
  System.IO.File.WriteAllBytes(@"C:\temp\uploadedFile", fileBytes);
  return Ok();
}

This code defines a HTTP POST method in an ASP.NET Core controller that accepts a base64 encoded file and decodes it back into its original format, saving it to a predefined path.

With these concepts and examples, you should now be well-equipped to handle base64 conversions in your C# projects!

Base64 Encoding and Decoding Bytes

Working with raw bytes and need to convert them to a base64 string? That’s easy in C#, here is how:

byte[] bytes = new byte[]{0x0A, 0x1F, 0x4B, 0x5C, 0x6D}; // The original bytes
string base64Bytes = Convert.ToBase64String(bytes); // Converting bytes to Base64
Console.WriteLine(base64Bytes);

This code will generate a base64 encoded string from the array of bytes.

Of course, you can also decode base64 strings back into bytes, as shown below:

string base64Bytes = "Ch9LXG0="; // The base64 encoded string
byte[] bytes = Convert.FromBase64String(base64Bytes); // Converting back to bytes
foreach (byte b in bytes)
{
    Console.WriteLine(b);
}

This code will decode a base64 encoded string back into bytes and print those bytes to the console.

Working with Data Streams

Streams are a fundamental concept in .NET and come up frequently when dealing with data. Thus, being able to convert streams to base64 and back can be very handy.

Let’s look at how you can convert a stream to base64:

Stream stream = File.OpenRead(@"C:\temp\file.txt"); // Open a stream
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length); // Read the stream into the buffer
string base64Stream = Convert.ToBase64String(buffer); // Convert the buffer to base64
Console.WriteLine(base64Stream);

This code reads a file into a stream, stores that stream into a byte array, and then converts that byte array into a base64 string.

And the reverse – loading a base64 string back into a stream:

string base64Stream = "..."; // Your base64 string here
byte[] buffer = Convert.FromBase64String(base64Stream); // Convert the base64 back to bytes
Stream stream = new MemoryStream(buffer); // Create a stream from the bytes

This code reads a base64 string back into a byte array and creates a stream from that byte array.

Reading Text Files as Base64

Suppose you want to read a text file and convert it directly to base64 for transmission over a network. Here’s how you can do so:

string text = File.ReadAllText(@"C:\temp\file.txt"); // Read the file as text
byte[] bytes = Encoding.UTF8.GetBytes(text); // Convert the text to bytes
string base64Text = Convert.ToBase64String(bytes); // Convert the bytes to base64
Console.WriteLine(base64Text);

The code will output the contents of the text file, read as base64.

Decoding Base64 to a Text File

Similarly, we might want to decode the received base64 data and write it back to a text file for further processing. This is achieved by:

string base64Text = "..."; // Your base64 string here
byte[] bytes = Convert.FromBase64String(base64Text); // Convert the base64 back to bytes
string text = Encoding.UTF8.GetString(bytes); // Convert the bytes back to text
File.WriteAllText(@"C:\temp\file.txt", text); // Write the text back to a file

This code converts a base64 string back into a byte array, converts that byte array back to a text string, and writes it back to a text file.

So whatever the data format you work with – strings, bytes, streams, or files – base64 is an invaluable tool that helps ensure data integrity while introducing you to core C# concepts such as encoding, decoding and handling text and binary data.

How to Keep Learning

Understanding the role that base64 encoding plays in C# is just the beginning of your programming and game development journey. There’s an entire universe of coding knowledge out there waiting to be discovered!

At Zenva, we aim to take you from beginner to professional through a variety of beginner-friendly but highly professional courses in programming, game development, and AI. Our catalog encompasses over 250 supported courses that help learners from all levels to boost their career, learn to code, create games, and earn certificates.

Dive Into Unity

If game development intrigues you, our Unity Game Development Mini-Degree could be the perfect next step for you. This comprehensive collection of courses teaches you to build cross-platform games using Unity, a favorite among both AAA and indie developers. The skills acquired can be applied to a multitude of areas, including virtual reality, augmented reality, and even non-gaming sectors such as architecture, film, and engineering. By the end, not only will you have a robust portfolio of Unity games and projects, but also an invaluable skill set with vast earning potential and career opportunities.

Want to explore more? Check out our broad collection of Unity courses right here.

Don’t stop at base64 – let your learning journey continue with us at Zenva, and broaden your horizons in the fascinating world of code.

Conclusion

Demystifying base64 and its application in C# is a big step forward in your programming journey. As you move from strings to files to images and beyond, you’ll find that base64 encoding and decoding opens up a world of possibilities in data handling and transmission.

Ready to broaden your horizons even more? Dive into our comprehensive coding courses at Zenva Academy and continue unlocking your potential. Whether it’s game creation, VR, AR, or machine learning – the sky’s the limit with Zenva. Build your bright future in coding and game development with us!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.