namespace XHWK.WKTool.Utils
{
using System;
using System.Configuration;
public static class ZConfigAppUtil
{
///
///返回app.config文件中appSettings配置节的value项
///
///
///
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;
}
///
///在app.config文件中appSettings配置节增加一对键值对
///
///
///
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));
}
}
}