Convert Strings to Base64 in C#
Base64 encoding is a method that transforms binary data into a text format, making it suitable for transmission over text-based protocols like email or storing complex data in a human-readable form. It does this by representing binary data as a string of ASCII characters using a set of 64 different characters (hence the name Base64). This ensures that the encoded data remains free from issues related to special characters that may be present in binary data.
using System;
using System.Text;
class Program
{
static void Main()
{
// Input string
string inputString = "Hello, Base64 Encoding!";
// Convert the string to Base64
string base64String = ConvertToBase64(inputString);
// Display the results
Console.WriteLine("Original String: " + inputString);
Console.WriteLine("Base64 Encoded String: " + base64String);
}
static string ConvertToBase64(string input)
{
byte[] bytes = Encoding.UTF8.GetBytes(input);
return Convert.ToBase64String(bytes);
}
}
The input string "Hello, Base64 Encoding!" is converted to its Base64 representation using the ConvertToBase64
method in the above program
Output:
Original String: Hello, Base64 Encoding!
Base64 Encoded String: SGVsbG8sIEJhc2U2NCBFbmNvZGluZyE=
Comments (0)