How do I encode and decode a base64 string?

前端 未结 10 2439
我在风中等你
我在风中等你 2020-11-22 03:41
  1. How do I return a base64 encoded string given a string?

  2. How do I decode a base64 encoded string into a string?

10条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 04:12

    A slight variation on andrew.fox answer, as the string to decode might not be a correct base64 encoded string:

    using System;
    
    namespace Service.Support
    {
        public static class Base64
        {
            public static string ToBase64(this System.Text.Encoding encoding, string text)
            {
                if (text == null)
                {
                    return null;
                }
    
                byte[] textAsBytes = encoding.GetBytes(text);
                return Convert.ToBase64String(textAsBytes);
            }
    
            public static bool TryParseBase64(this System.Text.Encoding encoding, string encodedText, out string decodedText)
            {
                if (encodedText == null)
                {
                    decodedText = null;
                    return false;
                }
    
                try
                {
                    byte[] textAsBytes = Convert.FromBase64String(encodedText);
                    decodedText = encoding.GetString(textAsBytes);
                    return true;
                }
                catch (Exception)
                {
                    decodedText = null;
                    return false;   
                }
            }
        }
    }
    

提交回复
热议问题