CoreUtils.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Security.Cryptography;
  6. using System.IO;
  7. using System.Reflection;
  8. using System.Security.Policy;
  9. using System.Text.RegularExpressions;
  10. using BasePaySdk.Request;
  11. namespace BasePaySdk
  12. {
  13. public class CoreUtils
  14. {
  15. public static string GetMD5Hash(string str)
  16. {
  17. //就是比string往后一直加要好的优化容器
  18. StringBuilder sb = new StringBuilder();
  19. using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
  20. {
  21. //将输入字符串转换为字节数组并计算哈希。
  22. byte[] data = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
  23. int length = data.Length;
  24. for (int i = 0; i < length; i++)
  25. sb.Append(data[i].ToString("X2"));
  26. }
  27. return sb.ToString();
  28. }
  29. public static byte[] File2Bytes(string FilePath)
  30. {
  31. if (!System.IO.File.Exists(FilePath))
  32. {
  33. return new byte[0];
  34. }
  35. FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
  36. byte[] buff = new byte[fs.Length];
  37. fs.Read(buff, 0, Convert.ToInt32(fs.Length));
  38. fs.Close();
  39. return buff;
  40. }
  41. public static string getOrignalString(Dictionary<string, object> dict) {
  42. Dictionary<string, object> params_SortedByKey = dict.OrderBy(p => p.Key).ToDictionary(p => p.Key, o => o.Value);
  43. StringBuilder orinalStr = new StringBuilder("");
  44. foreach (KeyValuePair<string, object> item in params_SortedByKey)
  45. {
  46. orinalStr.Append(item.Key)
  47. .Append("=")
  48. .Append(item.Value)
  49. .Append("&");
  50. }
  51. if (orinalStr.Equals(""))
  52. {
  53. return "";
  54. }
  55. else {
  56. orinalStr.Remove(orinalStr.Length - 1, 1);
  57. }
  58. return orinalStr.ToString();
  59. }
  60. public static void Log(string message)
  61. {
  62. if (BasePay.debug) {
  63. Console.WriteLine(message);
  64. }
  65. }
  66. public static Dictionary<string, Object> ObjToMap(BaseRequest obj)
  67. {
  68. Dictionary<string, Object> map = new Dictionary<string, Object>();
  69. FieldInfo[] list = obj.GetType().GetFields(BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly| BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
  70. foreach (FieldInfo p in list)
  71. {
  72. if (p.FieldType == typeof(string))
  73. {
  74. //Console.WriteLine("键:" + p.Name + ",值:" + p.GetValue(zone, null));
  75. map.Add(ToUnderLine(p.Name), Convert.ToString(p.GetValue(obj)));
  76. }
  77. }
  78. return map;
  79. }
  80. public static string ToUnderLine(string camelName)
  81. {
  82. return Regex.Replace(camelName, "([A-Z])", "_$1").ToLower().TrimStart('_');
  83. }
  84. }
  85. }