C# Tips and Tricks #18 – Encode and Decode a base64 string

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

image

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);
        }
    }
}
    

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...