|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- namespace XHWK.WKTool.Utils
- {
- using System;
- using System.Configuration;
-
- public static class ZConfigAppUtil
- {
- ///<summary>
- ///返回app.config文件中appSettings配置节的value项
- ///</summary>
- ///<param name="strKey"></param>
- ///<returns></returns>
- public static string GetVaule(string strKey)
- {
- return GetVaule(strKey, "app.config");
- }
-
- public static string GetVaule(string strKey, string filepath)
- {
- ExeConfigurationFileMap file = new ExeConfigurationFileMap { ExeConfigFilename = filepath };
- Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);
- foreach (string key in config.AppSettings.Settings.AllKeys)
- {
- if (key == strKey)
- {
- return config.AppSettings.Settings[strKey].Value;
- }
- }
- return null;
- }
-
- ///<summary>
- ///在app.config文件中appSettings配置节增加一对键值对
- ///</summary>
- ///<param name="newKey"></param>
- ///<param name="newValue"></param>
- public static void SetVaule(string newKey, string newValue)
- {
- SetVaule
- (
- newKey,
- newValue,
- "app.config"
- );
- }
-
- public static void SetVaule
- (
- string newKey,
- string newValue,
- string filepath
- )
- {
- ExeConfigurationFileMap file = new ExeConfigurationFileMap { ExeConfigFilename = filepath };
- Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);
- bool exist = false;
- foreach (string key in config.AppSettings.Settings.AllKeys)
- {
- if (key == newKey)
- {
- exist = true;
- }
- }
- if (exist)
- {
- config.AppSettings.Settings.Remove(newKey);
- }
- config.AppSettings.Settings.Add(newKey, newValue);
- config.Save(ConfigurationSaveMode.Modified);
- ConfigurationManager.RefreshSection("appSettings");
- }
-
- public static void Test()
- {
- SetVaule("ServerIp", "127.0.0.1");
- SetVaule("ServerPort", "10088");
- Console.WriteLine("ServerIp:" + GetVaule("ServerIp"));
- Console.WriteLine("ServerXXX:" + (GetVaule("ServerXXX") == null));
- }
- }
- }
|