Base64Provider.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /******************************************************************************
  2. * 作者: 季健国
  3. * 创建时间: 2012/6/6 22:19:26
  4. *
  5. *
  6. ******************************************************************************/
  7. using System;
  8. using System.Text;
  9. namespace Ant.Service.Common
  10. {
  11. /// <summary>
  12. /// 实现Base64编码与其它编码转换的类
  13. /// </summary>
  14. public class Base64Provider
  15. {
  16. private Base64Provider()
  17. {
  18. }
  19. /// <summary>
  20. /// 将其它编码的字符串转换成Base64编码的字符串
  21. /// </summary>
  22. /// <param name="source">要转换的字符串</param>
  23. /// <returns></returns>
  24. public static string EncodeBase64String(string source)
  25. {
  26. //如果字符串为空或者长度为0则抛出异常
  27. if (string.IsNullOrEmpty(source))
  28. {
  29. throw new ArgumentNullException("source", "不能为空。");
  30. }
  31. else
  32. {
  33. //将字符串转换成UTF-8编码的字节数组
  34. byte[] buffer = Encoding.UTF8.GetBytes(source);
  35. //将UTF-8编码的字节数组转换成Base64编码的字符串
  36. string result = Convert.ToBase64String(buffer);
  37. return result;
  38. }
  39. }
  40. /// <summary>
  41. /// 将Base64编码的字符串转换成其它编码的字符串
  42. /// </summary>
  43. /// <param name="result">要转换的Base64编码的字符串</param>
  44. /// <returns></returns>
  45. public static string DecodeBase64String(string result)
  46. {
  47. //如果字符串为空或者长度为0则抛出异常
  48. if (string.IsNullOrEmpty(result))
  49. {
  50. throw new ArgumentNullException("result", "不能为空。");
  51. }
  52. else
  53. {
  54. //将字符串转换成Base64编码的字节数组
  55. byte[] buffer = Convert.FromBase64String(result);
  56. //将字节数组转换成UTF-8编码的字符串
  57. string source = Encoding.UTF8.GetString(buffer);
  58. return source;
  59. }
  60. }
  61. }
  62. }