There are occassions where you might have to convert or encode a string to base64 and vice versa in C#.
How to encode and decode base64 string in C# ?
This can be achieved easily in C# using the Convert static class which provides the static methods ToBase64String and FromBase64String.
An example of how to implement this is shown below.
public static string EncodeBase64String(string input) { var plainText = System.Text.Encoding.UTF8.GetBytes(input); return Convert.ToBase64String(plainText); } public static string DecodeBase64String(string input) { var base64EncodedBytes = Convert.FromBase64String(input); return System.Text.Encoding.UTF8.GetString(base64EncodedBytes); }
Output
The complete code snippet that is used in this example is show below.
using System; using System.Linq; using System.Collections.Generic; namespace ConsoleApp1 { class Program { static void Main(string[] args) { string input = "Senthil"; string encodedString = EncodeBase64String(input); Console.WriteLine(encodedString); string decodedString = DecodeBase64String(encodedString); Console.WriteLine(decodedString); Console.ReadLine(); } public static string EncodeBase64String(string input) { var plainText = System.Text.Encoding.UTF8.GetBytes(input); return Convert.ToBase64String(plainText); } public static string DecodeBase64String(string input) { var base64EncodedBytes = Convert.FromBase64String(input); return System.Text.Encoding.UTF8.GetString(base64EncodedBytes); } } }