AppConfigHelper.cs 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  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. public static class AppConfigHelper
  11. {
  12. public static string Get(string key, string defaultVal = "")
  13. {
  14. var str = ConfigurationManager.AppSettings[key];
  15. if (string.IsNullOrWhiteSpace(str))
  16. return defaultVal;
  17. return str.Trim();
  18. }
  19. /// <summary>
  20. /// 获取App.config配置文件中appSettings节点中指定key的value
  21. /// <para>如果泛型为bool,则{"1","true","True","TRUE"}都会被转换成true,否则转换为false</para>
  22. /// <para>该方法支持int?、double?等可空类型的转换</para>
  23. /// </summary>
  24. /// <typeparam name="T"></typeparam>
  25. /// <param name="key"></param>
  26. /// <param name="defaultVal"></param>
  27. /// <returns></returns>
  28. public static T Get<T>(string key, T defaultVal = default)
  29. {
  30. var str = ConfigurationManager.AppSettings[key];
  31. if (string.IsNullOrWhiteSpace(str))
  32. {
  33. return defaultVal;
  34. }
  35. str = str.Trim();
  36. bool isNullable = typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>);
  37. if (isNullable)
  38. {
  39. NullableConverter nullableConverter = new NullableConverter(typeof(T));
  40. return (T)nullableConverter.ConvertFromString(str);
  41. }
  42. else if (typeof(T) == typeof(bool))
  43. {
  44. if (str.ToLower().Trim() == "true" || str.ToLower().Trim() == "1")
  45. {
  46. T boolVal = (T)Convert.ChangeType(true, typeof(T));
  47. return boolVal;
  48. }
  49. else
  50. {
  51. T boolVal = (T)Convert.ChangeType(false, typeof(T));
  52. return boolVal;
  53. }
  54. }
  55. else
  56. {
  57. T ret = (T)Convert.ChangeType(str, typeof(T));
  58. return ret;
  59. }
  60. }
  61. /// <summary>
  62. /// 如果参数小于0则返回0,否则返回原数字
  63. /// </summary>
  64. /// <param name="this"></param>
  65. /// <returns></returns>
  66. public static int NotLessThanZero(this int @this)
  67. {
  68. if (@this >= 0) return @this;
  69. return 0;
  70. }
  71. /// <summary>
  72. /// 为url字符串添加后缀
  73. /// </summary>
  74. /// <param name="this"></param>
  75. /// <param name="suffix"></param>
  76. /// <returns></returns>
  77. public static string AppendUrlSuffix(this string @this, string suffix)
  78. {
  79. if (suffix.StartsWith("/"))
  80. suffix = suffix.Substring(1);
  81. if (@this.EndsWith("/"))
  82. return $"{@this}{suffix}";
  83. else
  84. return $"{@this}/{suffix}";
  85. }
  86. public static void SetAppSetting(string key, string value)
  87. {
  88. Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
  89. if (ConfigurationManager.AppSettings[key] == null)
  90. {
  91. configuration.AppSettings.Settings.Add(key, value);
  92. }
  93. else
  94. {
  95. configuration.AppSettings.Settings[key].Value = value;
  96. }
  97. RefreshAndSaveSection(configuration);
  98. }
  99. public static void SetAppSetting<T>(string key, T value) where T : struct
  100. {
  101. var td = TypeDescriptor.GetConverter(typeof(T));
  102. var @string = td.ConvertToInvariantString(value);
  103. SetAppSetting(key, @string);
  104. }
  105. public static void SetAppSetting(Dictionary<string, string> settings)
  106. {
  107. if (settings == null || settings.Count == 0) return;
  108. Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
  109. foreach (var setting in settings)
  110. {
  111. string key = setting.Key;
  112. string value = setting.Value;
  113. if (ConfigurationManager.AppSettings[key] == null)
  114. {
  115. configuration.AppSettings.Settings.Add(key, value);
  116. }
  117. else
  118. {
  119. configuration.AppSettings.Settings[key].Value = value;
  120. }
  121. }
  122. RefreshAndSaveSection(configuration);
  123. }
  124. public static void RefreshAndSaveSection(Configuration config)
  125. {
  126. string configPath = config.FilePath;
  127. FileInfo fileInfo = new FileInfo(configPath);
  128. fileInfo.Attributes = FileAttributes.Normal;
  129. config.Save(ConfigurationSaveMode.Modified);
  130. ConfigurationManager.RefreshSection("appSettings");
  131. }
  132. }