How to encode and decode Base64 in C#?

In C#, you can use the ToBase64String method from the System.Convert class to achieve Base64 encoding, and use the FromBase64String method to achieve Base64 decoding.

Here is an example code demonstrating how to implement Base64 encoding and decoding.

using System;

class Program
{
    static void Main()
    {
        string originalString = "Hello, World!";
        
        // Base64编码
        string base64String = Base64Encode(originalString);
        Console.WriteLine("Base64编码后的字符串:{0}", base64String);
        
        // Base64解码
        string decodedString = Base64Decode(base64String);
        Console.WriteLine("Base64解码后的字符串:{0}", decodedString);
    }
    
    static string Base64Encode(string plainText)
    {
        byte[] plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
        return Convert.ToBase64String(plainTextBytes);
    }
    
    static string Base64Decode(string base64EncodedText)
    {
        byte[] base64EncodedBytes = Convert.FromBase64String(base64EncodedText);
        return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
    }
}

Output:

Base64编码后的字符串:SGVsbG8sIFdvcmxkIQ==
Base64解码后的字符串:Hello, World!

In the code above, we first define a string originalString, which is the original string to be encoded. Next, we call the Base64Encode method to encode this string into Base64, resulting in a new string base64String. Then, we use the Base64Decode method to decode base64String and obtain the decoded string decodedString.

The Base64Encode method first converts the original string into a byte array encoded in UTF-8, then uses the Convert.ToBase64String method to convert the byte array into a Base64 string and returns it.

The Base64Decode method first converts the Base64 encoded string into a byte array, then uses the System.Text.Encoding.UTF8.GetString method to convert the byte array into a UTF-8 encoded string, and returns it.

广告
Closing in 10 seconds
bannerAds