星火微课系统客户端
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

ZConfigAppUtil.cs 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. namespace XHWK.WKTool.Utils
  2. {
  3. using System;
  4. using System.Configuration;
  5. public static class ZConfigAppUtil
  6. {
  7. ///<summary>
  8. ///返回app.config文件中appSettings配置节的value项
  9. ///</summary>
  10. ///<param name="strKey"></param>
  11. ///<returns></returns>
  12. public static string GetVaule(string strKey)
  13. {
  14. return GetVaule(strKey, "app.config");
  15. }
  16. public static string GetVaule(string strKey, string filepath)
  17. {
  18. ExeConfigurationFileMap file = new ExeConfigurationFileMap { ExeConfigFilename = filepath };
  19. Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);
  20. foreach (string key in config.AppSettings.Settings.AllKeys)
  21. {
  22. if (key == strKey)
  23. {
  24. return config.AppSettings.Settings[strKey].Value;
  25. }
  26. }
  27. return null;
  28. }
  29. ///<summary>
  30. ///在app.config文件中appSettings配置节增加一对键值对
  31. ///</summary>
  32. ///<param name="newKey"></param>
  33. ///<param name="newValue"></param>
  34. public static void SetVaule(string newKey, string newValue)
  35. {
  36. SetVaule
  37. (
  38. newKey,
  39. newValue,
  40. "app.config"
  41. );
  42. }
  43. public static void SetVaule
  44. (
  45. string newKey,
  46. string newValue,
  47. string filepath
  48. )
  49. {
  50. ExeConfigurationFileMap file = new ExeConfigurationFileMap { ExeConfigFilename = filepath };
  51. Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);
  52. bool exist = false;
  53. foreach (string key in config.AppSettings.Settings.AllKeys)
  54. {
  55. if (key == newKey)
  56. {
  57. exist = true;
  58. }
  59. }
  60. if (exist)
  61. {
  62. config.AppSettings.Settings.Remove(newKey);
  63. }
  64. config.AppSettings.Settings.Add(newKey, newValue);
  65. config.Save(ConfigurationSaveMode.Modified);
  66. ConfigurationManager.RefreshSection("appSettings");
  67. }
  68. public static void Test()
  69. {
  70. SetVaule("ServerIp", "127.0.0.1");
  71. SetVaule("ServerPort", "10088");
  72. Console.WriteLine(@"ServerIp:" + GetVaule("ServerIp"));
  73. Console.WriteLine(@"ServerXXX:" + (GetVaule("ServerXXX") == null));
  74. }
  75. }
  76. }