ConfigHelper.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace Common
  8. {
  9. /// <summary>
  10. /// 配置文件操作帮助类
  11. /// </summary>
  12. public sealed class ConfigHelper
  13. {
  14. /// <summary>
  15. /// 获取链接字符串
  16. /// </summary>
  17. /// <param name="name"></param>
  18. /// <returns></returns>
  19. public static string GetConnectionString(string name)
  20. {
  21. //Data Source=101.200.33.46;database=LottomatBaseDB;uid=sa;pwd=zhaoyi18284594619;
  22. string reg = @"Data Source=(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)";
  23. if (StringHelper.QuickValidate(reg, name))
  24. return name;
  25. string res = ConfigurationManager.ConnectionStrings[name].ConnectionString.ToString();
  26. return res;
  27. }
  28. /// <summary>
  29. /// 根据Key获取配置值
  30. /// </summary>
  31. /// <param name="key"></param>
  32. /// <returns></returns>
  33. public static string GetValue(string key)
  34. {
  35. try
  36. {
  37. string res = ConfigurationManager.AppSettings[key].ToString();
  38. return res;
  39. }
  40. catch (Exception)
  41. {
  42. return "";
  43. }
  44. }
  45. /// <summary>
  46. /// 获取配置文件节点
  47. /// </summary>
  48. /// <typeparam name="T"></typeparam>
  49. /// <param name="sectionName"></param>
  50. /// <returns></returns>
  51. public static T GetSection<T>(string sectionName) where T : class, new()
  52. {
  53. T res = ConfigurationManager.GetSection(sectionName) as T;
  54. return res;
  55. }
  56. }
  57. }