如何對base 64字符串進行編碼和解碼?如何返回給定字符串的base 64編碼字符串?如何將base 64編碼的字符串解碼為字符串?
3 回答
幕布斯6054654
TA貢獻1876條經驗 獲得超7個贊
使用擴展方法對類進行編碼。理由是某人可能需要支持不同類型的編碼(不僅僅是UTF 8)。 另一個改進是在空項的空結果方面失敗-它在現實生活中非常有用,并且支持X=decode(encode(X)的等價性。
usingusing 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);
}
}}- 3 回答
- 0 關注
- 695 瀏覽
添加回答
舉報
0/150
提交
取消
