1 public class Base64Provider 2 { 3 private Base64Provider() 4 { 5 } 6 /// <summary> 7 /// 将其它编码的字符串转换成Base64编码的字符串 8 /// </summary> 9 /// <param name="source">要转换的字符串</param> 10 /// <returns></returns> 11 public static string EncodeBase64String(string source) 12 { 13 //如果字符串为空或者长度为0则抛出异常 14 if (string.IsNullOrEmpty(source)) 15 { 16 throw new ArgumentNullException("source", "不能为空。"); 17 } 18 else 19 { 20 //将字符串转换成UTF-8编码的字节数组 21 byte[] buffer = Encoding.UTF8.GetBytes(source); 22 //将UTF-8编码的字节数组转换成Base64编码的字符串 23 string result = Convert.ToBase64String(buffer); 24 return result; 25 } 26 } 27 /// <summary> 28 /// 将Base64编码的字符串转换成其它编码的字符串 29 /// </summary> 30 /// <param name="result">要转换的Base64编码的字符串</param> 31 /// <returns></returns> 32 public static string DecodeBase64String(string result) 33 { 34 //如果字符串为空或者长度为0则抛出异常 35 if (string.IsNullOrEmpty(result)) 36 { 37 throw new ArgumentNullException("result", "不能为空。"); 38 } 39 else 40 { 41 //将字符串转换成Base64编码的字节数组 42 byte[] buffer = Convert.FromBase64String(result); 43 //将字节数组转换成UTF-8编码的字符串 44 string source = Encoding.UTF8.GetString(buffer); 45 return source; 46 } 47 } 48 }