[C#] Proper Handling of Base64 Conversion and Encoding for Text Data

目次

Overview

To convert text data into Base64 format, you must first convert the text into a byte array. This article explains the implementation pattern for correctly converting between strings and Base64 by combining System.Text.Encoding and System.Convert.

Specifications (Input/Output)

  • Input
    • Encoding: Any string.
    • Decoding: A Base64 formatted string.
  • Output
    • Encoding: A Base64-encoded ASCII string.
    • Decoding: The restored original string.
  • Error Handling
    • If you try to decode an invalid Base64 string, a FormatException will occur. This should be caught appropriately.

Basic Usage

The following example uses UTF-8 encoding, which is the most common standard for the web.

string source = "Sample Text";

// String -> Base64
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(source);
string encoded = Convert.ToBase64String(bytes);

// Base64 -> String
byte[] decodedBytes = Convert.FromBase64String(encoded);
string decoded = System.Text.Encoding.UTF8.GetString(decodedBytes);

Full Code

This console application accepts an input string from the user, converts it to Base64, and then verifies that it returns to the original text after decoding.

using System;
using System.Text;

class Program
{
    static void Main()
    {
        try
        {
            // 1. Target string (e.g., JSON data or message body)
            string message = "C# Programming & Base64";
            Console.WriteLine($"[Original] {message}");

            // Encoding to use (UTF-8 is generally recommended)
            Encoding encoding = Encoding.UTF8;

            // ---------------------------------------------------------
            // 2. Encoding Process (String -> byte[] -> Base64)
            // ---------------------------------------------------------
            // Strings cannot be converted to Base64 directly; convert to byte array first
            byte[] messageBytes = encoding.GetBytes(message);
            
            // Convert byte array to Base64 string
            string base64String = Convert.ToBase64String(messageBytes);
            
            Console.WriteLine($"[Encoded ] {base64String}");

            // ---------------------------------------------------------
            // 3. Decoding Process (Base64 -> byte[] -> String)
            // ---------------------------------------------------------
            // Convert Base64 string back to byte array
            byte[] restoredBytes = Convert.FromBase64String(base64String);
            
            // Convert byte array back to string (Use the same Encoding as encoding process)
            string restoredMessage = encoding.GetString(restoredBytes);
            
            Console.WriteLine($"[Decoded ] {restoredMessage}");

            // ---------------------------------------------------------
            // 4. Verification
            // ---------------------------------------------------------
            if (message == restoredMessage)
            {
                Console.WriteLine("[Check   ] Successfully restored.");
            }
        }
        catch (FormatException)
        {
            Console.WriteLine("[Error   ] Invalid Base64 string.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"[Error   ] {ex.Message}");
        }
    }
}

Execution Result Example

[Original] C# Programming & Base64
[Encoded ] QyMgUHJvZ3JhbW1pbmcgJiBCYXNlNjQ=
[Decoded ] C# Programming & Base64
[Check   ] Successfully restored.

Customization Points

  • Changing Character Codes: If you need Shift_JIS or Unicode (UTF-16) for legacy systems, change the encoding to Encoding.GetEncoding("Shift_JIS") or Encoding.Unicode.
  • Asynchronous Processing: Since conversion is a CPU-bound task, there are no built-in async methods. However, when combining this with file I/O or web communication, it is common to integrate it into an async flow using MemoryStream.

Points of Caution

  • Encoding Mismatch: If you use different encodings for encoding and decoding, the text will become corrupted. Mixing up UTF-8 and Shift_JIS is a common cause of bugs.
  • Data Size Increase: Base64 encoding increases the data size by approximately 33% compared to the original. Be mindful of memory usage when handling large text data.
  • Security: Base64 is not encryption. Anyone can read the original text by decoding it. Always use encryption when handling passwords or personal information.

Application

Simplification with Extension Methods

If you perform conversions frequently, defining extension methods for the string type is convenient.

using System;
using System.Text;

public static class Base64Extensions
{
    // Encodes the string into Base64
    public static string ToBase64(this string text, Encoding encoding = null)
    {
        if (string.IsNullOrEmpty(text)) return string.Empty;
        var enc = encoding ?? Encoding.UTF8;
        return Convert.ToBase64String(enc.GetBytes(text));
    }

    // Decodes the string assuming it is Base64
    public static string DecodeBase64(this string base64, Encoding encoding = null)
    {
        if (string.IsNullOrEmpty(base64)) return string.Empty;
        var enc = encoding ?? Encoding.UTF8;
        return enc.GetString(Convert.FromBase64String(base64));
    }
}

Summary

Converting strings to Base64 involves an intermediate step of converting to a byte array, so choosing the correct encoding is very important. You can prevent corrupted text issues by using a unified character code (usually UTF-8) throughout your system. Also, remember that Base64 is a reversible conversion and does not provide security protection.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次