如何对base 64字符串进行编码和解码?

如何对base 64字符串进行编码和解码?

  1. 如何返回给定字符串的base 64编码字符串?

  2. 如何将base 64编码的字符串解码为字符串?


元芳怎么了
浏览 634回答 3
3回答

幕布斯6054654

我正在与一些简洁的特性分享我的实现:使用扩展方法对类进行编码。理由是某人可能需要支持不同类型的编码(不仅仅是UTF 8)。另一个改进是在空项的空结果方面失败-它在现实生活中非常有用,并且支持X=decode(encode(X)的等价性。备注:要使用扩展方法,请记住不得不(!)使用using关键字(在本例中)using MyApplication.Helpers.Encoding).代码:namespace MyApplication.Helpers.Encoding{     public static class EncodingForBase64     {         public static string EncodeBase64(this System.Text.Encoding encoding, string text)         {             if (text == null)             {                 return null;             }             byte[] textAsBytes = encoding.GetBytes(text);             return System.Convert.ToBase64String(textAsBytes);         }         public static string DecodeBase64(this System.Text.Encoding encoding, string encodedText)         {             if (encodedText == null)             {                 return null;             }             byte[] textAsBytes = System.Convert.FromBase64String(encodedText);             return encoding.GetString(textAsBytes);         }     }}用法示例:using MyApplication.Helpers.Encoding; // !!!namespace ConsoleApplication1{     class Program     {         static void Main(string[] args)         {             Test1();             Test2();         }         static void Test1()         {             string textEncoded = System.Text.Encoding.UTF8.EncodeBase64("test1...");             System.Diagnostics.Debug.Assert(textEncoded == "dGVzdDEuLi4=");             string textDecoded = System.Text.Encoding.UTF8.DecodeBase64(textEncoded);             System.Diagnostics.Debug.Assert(textDecoded == "test1...");         }         static void Test2()         {             string textEncoded = System.Text.Encoding.UTF8.EncodeBase64(null);             System.Diagnostics.Debug.Assert(textEncoded == null);             string textDecoded = System.Text.Encoding.UTF8.DecodeBase64(textEncoded);             System.Diagnostics.Debug.Assert(textDecoded == null);         }     }}
打开App,查看更多内容
随时随地看视频慕课网APP