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

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...