CommonUtil.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System.Xml;
  2. using System.Xml.Linq;
  3. using System.Xml.Serialization;
  4. namespace Admin.NET.Core;
  5. /// <summary>
  6. /// 通用工具类
  7. /// </summary>
  8. public static class CommonUtil
  9. {
  10. /// <summary>
  11. /// 生成百分数
  12. /// </summary>
  13. /// <param name="PassCount"></param>
  14. /// <param name="allCount"></param>
  15. /// <returns></returns>
  16. public static string ExecPercent(decimal PassCount, decimal allCount)
  17. {
  18. string res = "";
  19. if (allCount > 0)
  20. {
  21. var value = (double)Math.Round(PassCount / allCount * 100, 1);
  22. if (value < 0)
  23. res = Math.Round(value + 5 / Math.Pow(10, 0 + 1), 0, MidpointRounding.AwayFromZero).ToString();
  24. else
  25. res = Math.Round(value, 0, MidpointRounding.AwayFromZero).ToString();
  26. }
  27. if (res == "") res = "0";
  28. return res + "%";
  29. }
  30. /// <summary>
  31. /// 获取服务地址
  32. /// </summary>
  33. /// <returns></returns>
  34. public static string GetLocalhost()
  35. {
  36. return $"{App.HttpContext.Request.Scheme}://{App.HttpContext.Request.Host.Value}";
  37. }
  38. /// <summary>
  39. /// 对象序列化XML
  40. /// </summary>
  41. /// <typeparam name="T"></typeparam>
  42. /// <param name="obj"></param>
  43. /// <returns></returns>
  44. public static string SerializeObjectToXml<T>(T obj)
  45. {
  46. if (obj == null) return string.Empty;
  47. var xs = new XmlSerializer(obj.GetType());
  48. var stream = new MemoryStream();
  49. var setting = new XmlWriterSettings
  50. {
  51. Encoding = new UTF8Encoding(false), // 不包含BOM
  52. Indent = true // 设置格式化缩进
  53. };
  54. using (var writer = XmlWriter.Create(stream, setting))
  55. {
  56. var ns = new XmlSerializerNamespaces();
  57. ns.Add("", ""); // 去除默认命名空间
  58. xs.Serialize(writer, obj, ns);
  59. }
  60. return Encoding.UTF8.GetString(stream.ToArray());
  61. }
  62. /// <summary>
  63. /// 字符串转XML格式
  64. /// </summary>
  65. /// <param name="xmlStr"></param>
  66. /// <returns></returns>
  67. public static XElement SerializeStringToXml(string xmlStr)
  68. {
  69. try
  70. {
  71. return XElement.Parse(xmlStr);
  72. }
  73. catch
  74. {
  75. return null;
  76. }
  77. }
  78. }