如何对 string 进行Base64编码,解码?
生活随笔
收集整理的這篇文章主要介紹了
如何对 string 进行Base64编码,解码?
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
咨詢區
Kevin Driedger:
如何將指定的 string 編碼成 base64。
如何將 base64 解碼成 string。
回答區
andrew.fox:
我來分享下對這個問題的處理吧:
對 Encoding 類進行擴展,當然擴展方法還支持各種編碼格式,不僅僅是 UTF8。
還一個好處是對 null 的支持,畢竟在真實項目中你總會遇到的。
代碼如下:
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);}} }Zeigeist:
其實這就一行代碼的事。。。
Encode:
Decode:
點評區
看了下 Convert.FromBase64String 的源碼,在入參為null的情況下會拋出異常。
public?static?string?ToBase64String(byte[]?inArray) {if?(inArray?==?null){throw?new?ArgumentNullException("inArray");}return?ToBase64String(inArray,?0,?inArray.Length,?Base64FormattingOptions.None); }我覺得項目中這種反饋肯定是不能接受的,所以哈,用一個擴展方法挺好,學習了!
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的如何对 string 进行Base64编码,解码?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Goreplay来做流量回放
- 下一篇: 精简ABP的模块依赖