Decode a base64 string (UTF8) - CSharp System

CSharp examples for System:String Base64

Description

Decode a base64 string (UTF8)

Demo Code


using System.Text.RegularExpressions;
using System.Text;
using System.Globalization;
using System;// w w  w. j  a va  2s .  c o  m

public class Main{
        /// <summary>
        /// Decode a base64 string (UTF8)
        /// </summary>
        /// <param name="encodedValue"></param>
        /// <returns></returns>
        public static string Base64Utf8Decode(string encodedValue)
        {
            if (String.IsNullOrEmpty(encodedValue))
                return null;

            System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
            System.Text.Decoder utf8Decode = encoder.GetDecoder();
            byte[] todecode_byte = null;

            try
            {
                todecode_byte = Convert.FromBase64String(encodedValue);
            }
            catch (FormatException)
            {
                return null;
            }

            int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
            char[] decoded_char = new char[charCount];
            utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
            return new String(decoded_char);
        }
}

Related Tutorials