How to convert string to base64 in C#
By Tan Lee Published on Dec 16, 2024 268
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.
Categories
Popular Posts
Material Lite Admin Template
Nov 14, 2024
Simple Responsive Login Page
Nov 11, 2024
Freedash bootstrap lite
Nov 13, 2024
Dash UI HTML5 Admin Dashboard Template
Nov 18, 2024