12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- using Newtonsoft.Json.Linq;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Configuration;
- using System.Linq;
- using System.Runtime.Remoting;
- using System.Text;
- using System.Threading.Tasks;
- namespace XdCxRhDW.Framework
- {
- public static class AppConfigHelper
- {
- public static string Get(string key, string defaultVal = "")
- {
- var str = ConfigurationManager.AppSettings[key];
- if (string.IsNullOrWhiteSpace(str))
- return defaultVal;
- return str.Trim();
- }
- /// <summary>
- /// 获取App.config配置文件中appSettings节点中指定key的value
- /// <para>如果泛型为bool,则{"1","true","True","TRUE"}都会被转换成true,否则转换为false</para>
- /// <para>该方法支持int?、double?等可空类型的转换</para>
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="key"></param>
- /// <param name="defaultVal"></param>
- /// <returns></returns>
- public static T Get<T>(string key, T defaultVal = default)
- {
- var str = ConfigurationManager.AppSettings[key];
- if (string.IsNullOrWhiteSpace(str))
- {
- return defaultVal;
- }
- str = str.Trim();
- bool isNullable = typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>);
- if (isNullable)
- {
- NullableConverter nullableConverter = new NullableConverter(typeof(T));
- return (T)nullableConverter.ConvertFromString(str);
- }
- else if (typeof(T) == typeof(bool))
- {
- if (str.ToLower().Trim() == "true" || str.ToLower().Trim() == "1")
- {
- T boolVal = (T)Convert.ChangeType(true, typeof(T));
- return boolVal;
- }
- else
- {
- T boolVal = (T)Convert.ChangeType(false, typeof(T));
- return boolVal;
- }
- }
- else
- {
- T ret = (T)Convert.ChangeType(str, typeof(T));
- return ret;
- }
- }
- /// <summary>
- /// 如果参数小于0则返回0,否则返回原数字
- /// </summary>
- /// <param name="this"></param>
- /// <returns></returns>
- public static int NotLessThanZero(this int @this)
- {
- if (@this >= 0) return @this;
- return 0;
- }
- /// <summary>
- /// 为url字符串添加后缀
- /// </summary>
- /// <param name="this"></param>
- /// <param name="suffix"></param>
- /// <returns></returns>
- public static string AppendUrlSuffix(this string @this, string suffix)
- {
- if (suffix.StartsWith("/"))
- suffix = suffix.Substring(1);
- if (@this.EndsWith("/"))
- return $"{@this}{suffix}";
- else
- return $"{@this}/{suffix}";
- }
- }
- }
|