您的位置:首页 > 编程语言 > C#

C# 读取和修改指定config文件内的配置

2015-06-18 13:23 781 查看
由于修改默认的app.config文件,总是会在执行完后被旧文件覆盖,不清楚是什么原因。所以替代办法是在另外一个自定义的配置文件中进行读写。

1.读取

//读取Debug文件夹下自定义的PrintSetting.config中的配置信息
private string getConfig(string key)
{
string fileName = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\PrintSetting.config";
ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = fileName;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
return config.AppSettings.Settings[key].Value == null ? "" : config.AppSettings.Settings[key].Value;
}


2.修改

//修改配置信息
private void setConfig(string key, string value)
{
XmlDocument xml = new XmlDocument();
string fileName = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\PrintSetting.config";
xml.Load(fileName);
XmlNodeList nodes = xml.GetElementsByTagName("add");
for (int i = 0; i < nodes.Count; i++)
{
XmlAttribute att = nodes[i].Attributes["key"];
if (att.Value == key)
{
att = nodes[i].Attributes["value"];
att.Value = value;
break;
}
}
xml.Save(fileName);
System.Configuration.ConfigurationManager.RefreshSection("appSettings");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: