How do I encode and decode a base64 string?

前端 未结 10 2297
我在风中等你
我在风中等你 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:23

        using System;
        using System.Text;
    
        public static class Base64Conversions
        {
            public static string EncodeBase64(this string text, Encoding encoding = null)
            { 
                if (text == null) return null;
    
                encoding = encoding ?? Encoding.UTF8;
                var bytes = encoding.GetBytes(text);
                return Convert.ToBase64String(bytes);
            }
    
            public static string DecodeBase64(this string encodedText, Encoding encoding = null)
            {
                if (encodedText == null) return null;
    
                encoding = encoding ?? Encoding.UTF8;
                var bytes = Convert.FromBase64String(encodedText);
                return encoding.GetString(bytes);
            }
        }
    

    Usage

        var text = "Sample Text";
        var base64 = text.EncodeBase64();
        base64 = text.EncodeBase64(Encoding.UTF8); //or with Encoding
    

提交回复
热议问题