StringHelper.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Text;
  5. namespace KYFramework
  6. {
  7. public static class StringHelper
  8. {
  9. public static IEnumerable<byte> ToBytes(this string str)
  10. {
  11. byte[] byteArray = Encoding.Default.GetBytes(str);
  12. return byteArray;
  13. }
  14. public static byte[] ToByteArray(this string str)
  15. {
  16. byte[] byteArray = Encoding.Default.GetBytes(str);
  17. return byteArray;
  18. }
  19. public static byte[] ToUtf8(this string str)
  20. {
  21. byte[] byteArray = Encoding.UTF8.GetBytes(str);
  22. return byteArray;
  23. }
  24. public static byte[] HexToBytes(this string hexString)
  25. {
  26. if (hexString.Length % 2 != 0)
  27. {
  28. throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "The binary key cannot have an odd number of digits: {0}", hexString));
  29. }
  30. var hexAsBytes = new byte[hexString.Length / 2];
  31. for (int index = 0; index < hexAsBytes.Length; index++)
  32. {
  33. string byteValue = "";
  34. byteValue += hexString[index * 2];
  35. byteValue += hexString[index * 2 + 1];
  36. hexAsBytes[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
  37. }
  38. return hexAsBytes;
  39. }
  40. public static string Fmt(this string text, params object[] args)
  41. {
  42. return string.Format(text, args);
  43. }
  44. public static string ListToString<T>(this List<T> list)
  45. {
  46. StringBuilder sb = new StringBuilder();
  47. foreach (T t in list)
  48. {
  49. sb.Append(t);
  50. sb.Append(",");
  51. }
  52. return sb.ToString();
  53. }
  54. public static string MessageToStr(object message)
  55. {
  56. return MongoHelper.ToJson(message);
  57. }
  58. }
  59. }