Try it yourself with our free Base64 tool — runs entirely in your browser, no signup needed.

How to Base64 decode in C#

How to Base64 decode in C#

Base64 decoding is a fundamental operation in software development, particularly when working with data exchange formats like JSON, XML, or when transmitting binary data over text-based protocols. In C#, Base64 decoding is a straightforward process that can be achieved using the built-in Convert class. This guide will walk you through the process of Base64 decoding in C#, covering the basics, common edge cases, and performance tips.

Quick Example

using System;

class Base64Decoder
{
    public static string DecodeBase64(string input)
    {
        byte[] bytes = Convert.FromBase64String(input);
        return System.Text.Encoding.UTF8.GetString(bytes);
    }

    public static void Main()
    {
        string encodedString = "SGVsbG8gd29ybGQh";
        string decodedString = DecodeBase64(encodedString);
        Console.WriteLine(decodedString); // Output: "Hello world!"
    }
}

This example demonstrates the most common use case for Base64 decoding: decoding a Base64-encoded string to retrieve the original text.

Step-by-Step Breakdown

Let's break down the code line by line:

  1. using System; - This line imports the System namespace, which contains the Convert class used for Base64 decoding.
  2. public static string DecodeBase64(string input) - This defines a static method DecodeBase64 that takes a Base64-encoded string as input and returns the decoded string.
  3. byte[] bytes = Convert.FromBase64String(input); - This line uses the Convert.FromBase64String method to convert the Base64-encoded string to a byte array.
  4. return System.Text.Encoding.UTF8.GetString(bytes); - This line converts the byte array to a string using the UTF-8 encoding scheme, which is the most common encoding scheme for text data.

Handling Edge Cases

Empty/Null Input

public static string DecodeBase64(string input)
{
    if (string.IsNullOrEmpty(input))
    {
        throw new ArgumentException("Input cannot be null or empty", nameof(input));
    }
    // ...
}

In this example, we add a simple null check to throw an ArgumentException if the input is null or empty.

Invalid Input

public static string DecodeBase64(string input)
{
    try
    {
        byte[] bytes = Convert.FromBase64String(input);
        // ...
    }
    catch (FormatException ex)
    {
        throw new ArgumentException("Invalid Base64 input", nameof(input), ex);
    }
}

In this example, we wrap the Convert.FromBase64String call in a try-catch block to catch any FormatException exceptions that may be thrown if the input is invalid.

Large Input

public static string DecodeBase64(string input)
{
    if (input.Length > 10000)
    {
        throw new ArgumentException("Input is too large", nameof(input));
    }
    // ...
}

In this example, we add a simple length check to throw an ArgumentException if the input is too large.

Unicode/Special Characters

public static string DecodeBase64(string input)
{
    byte[] bytes = Convert.FromBase64String(input);
    return System.Text.Encoding.UTF8.GetString(bytes);
}

In this example, we use the UTF-8 encoding scheme to handle Unicode and special characters correctly.

Common Mistakes

Mistake 1: Using the Wrong Encoding Scheme

// Wrong code
return System.Text.Encoding.ASCII.GetString(bytes);

// Corrected code
return System.Text.Encoding.UTF8.GetString(bytes);

Using the wrong encoding scheme can lead to incorrect decoding of Unicode and special characters.

Mistake 2: Not Handling Edge Cases

// Wrong code
byte[] bytes = Convert.FromBase64String(input);

// Corrected code
try
{
    byte[] bytes = Convert.FromBase64String(input);
    // ...
}
catch (FormatException ex)
{
    throw new ArgumentException("Invalid Base64 input", nameof(input), ex);
}

Not handling edge cases can lead to unexpected exceptions and errors.

Mistake 3: Not Checking for Null Input

// Wrong code
byte[] bytes = Convert.FromBase64String(input);

// Corrected code
if (string.IsNullOrEmpty(input))
{
    throw new ArgumentException("Input cannot be null or empty", nameof(input));
}

Not checking for null input can lead to NullReferenceException exceptions.

Performance Tips

  1. Use the Convert.FromBase64String method: This method is optimized for performance and is the recommended way to decode Base64 strings in C#.
  2. Use the UTF-8 encoding scheme: The UTF-8 encoding scheme is the most efficient encoding scheme for text data and is the recommended choice for Base64 decoding.
  3. Avoid unnecessary conversions: Avoid converting the decoded byte array to a string unnecessarily, as this can lead to performance overhead.

FAQ

Q: What is the difference between Base64 encoding and decoding?

A: Base64 encoding converts binary data to a text representation, while Base64 decoding converts the text representation back to the original binary data.

Q: How do I install the System namespace?

A: The System namespace is part of the .NET Framework and does not require installation.

Q: Can I use Base64 decoding for large files?

A: While it is technically possible to use Base64 decoding for large files, it is not recommended due to performance and memory constraints.

Q: How do I handle invalid input?

A: You can handle invalid input by wrapping the Convert.FromBase64String call in a try-catch block and catching any FormatException exceptions that may be thrown.

Q: Can I use Base64 decoding for Unicode text?

A: Yes, you can use Base64 decoding for Unicode text by using the UTF-8 encoding scheme.

AI agent tools available. The CodeTidy MCP Server gives Claude, Cursor, and other AI agents access to 60+ developer tools. One command: npx @codetidy/mcp