AppConfigHelper.cs 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using Newtonsoft.Json.Linq;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Configuration;
  6. using System.Linq;
  7. using System.Runtime.Remoting;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. namespace XdCxRhDW.Framework
  11. {
  12. public static class AppConfigHelper
  13. {
  14. public static string Get(string key, string defaultVal = "")
  15. {
  16. var str = ConfigurationManager.AppSettings[key];
  17. if (string.IsNullOrWhiteSpace(str))
  18. return defaultVal;
  19. return str.Trim();
  20. }
  21. /// <summary>
  22. /// 获取App.config配置文件中appSettings节点中指定key的value
  23. /// <para>如果泛型为bool,则{"1","true","True","TRUE"}都会被转换成true,否则转换为false</para>
  24. /// <para>该方法支持int?、double?等可空类型的转换</para>
  25. /// </summary>
  26. /// <typeparam name="T"></typeparam>
  27. /// <param name="key"></param>
  28. /// <param name="defaultVal"></param>
  29. /// <returns></returns>
  30. public static T Get<T>(string key, T defaultVal = default)
  31. {
  32. var str = ConfigurationManager.AppSettings[key];
  33. if (string.IsNullOrWhiteSpace(str))
  34. {
  35. return defaultVal;
  36. }
  37. str = str.Trim();
  38. bool isNullable = typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>);
  39. if (isNullable)
  40. {
  41. NullableConverter nullableConverter = new NullableConverter(typeof(T));
  42. return (T)nullableConverter.ConvertFromString(str);
  43. }
  44. else if (typeof(T) == typeof(bool))
  45. {
  46. if (str.ToLower().Trim() == "true" || str.ToLower().Trim() == "1")
  47. {
  48. T boolVal = (T)Convert.ChangeType(true, typeof(T));
  49. return boolVal;
  50. }
  51. else
  52. {
  53. T boolVal = (T)Convert.ChangeType(false, typeof(T));
  54. return boolVal;
  55. }
  56. }
  57. else
  58. {
  59. T ret = (T)Convert.ChangeType(str, typeof(T));
  60. return ret;
  61. }
  62. }
  63. /// <summary>
  64. /// 如果参数小于0则返回0,否则返回原数字
  65. /// </summary>
  66. /// <param name="this"></param>
  67. /// <returns></returns>
  68. public static int NotLessThanZero(this int @this)
  69. {
  70. if (@this >= 0) return @this;
  71. return 0;
  72. }
  73. /// <summary>
  74. /// 为url字符串添加后缀
  75. /// </summary>
  76. /// <param name="this"></param>
  77. /// <param name="suffix"></param>
  78. /// <returns></returns>
  79. public static string AppendUrlSuffix(this string @this, string suffix)
  80. {
  81. if (suffix.StartsWith("/"))
  82. suffix = suffix.Substring(1);
  83. if (@this.EndsWith("/"))
  84. return $"{@this}{suffix}";
  85. else
  86. return $"{@this}/{suffix}";
  87. }
  88. }
  89. }