How to convert string to base64 in C#

By FoxLearn 12/16/2024 7:29:41 AM   37
In C#, you can convert a string to a Base64 encoded string using the Convert.ToBase64String method.

C# Convert String to Base64

First, we convert the string into a byte array using the Encoding.UTF8.GetBytes method, then use Convert.ToBase64String to convert the byte array to a Base64 string.

// c# convert string to base64
public static string ConvertStringToBase64(string value)
{
    // Step 1: Convert the string to a byte array
    byte[] byteArray = Encoding.UTF8.GetBytes(value);

    // Step 2: Convert the byte array to a Base64 encoded string
    string base64String = Convert.ToBase64String(byteArray);
    return base64String;
}

Main method.

using System;
using System.Text;

class Program
{
    static void Main()
    {
        string str = "C# Programming";        
        string base64String = ConvertStringToBase64(str);        
        // Output the Base64 encoded string
        Console.WriteLine("Base64 Encoded: " + base64String);
    }
}

Output:

Base64 Encoded: QyMgUHJvZ3JhbW1pbmc=

This code converts "C# Programming" to "QyMgUHJvZ3JhbW1pbmc=", which is the Base64 encoded representation of the string.