Published: September 12 2020

C# - Encode and Decode Base64 Strings

This is a super quick post to share the below couple of extension methods that simplify encoding and decoding base64 strings in C#.

using System;
using System.Text;

namespace App.Helpers
{
    public static class ExtensionMethods
    {
        public static string EncodeBase64(this string value)
        {
            var valueBytes = Encoding.UTF8.GetBytes(value);
            return Convert.ToBase64String(valueBytes);
        }

        public static string DecodeBase64(this string value)
        {
            var valueBytes = System.Convert.FromBase64String(value);
            return Encoding.UTF8.GetString(valueBytes);
        }
    }
}


Encoding a Base64 String in C#

This is how to encode a normal string as a base64 string using the above EncodeBase64() extension method.

var base64EncodedString = "normal string".EncodeBase64();


Decoding a Base64 String in C#

This is how to decode a base64 encoded string using the above DecodeBase64() extension method.

var normalString = base64EncodedString.DecodeBase64();

 


Need Some C# Help?

Search fiverr for freelance C# developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by