Published:

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

 

Subscribe or Follow Me For Updates

Subscribe to my YouTube channel or follow me on Twitter or GitHub to be notified when I post new content.

 


Supported by