当前位置:首页 > Windows程序 > 正文

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

2021-05-25 Windows程序

由于修改默认的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"); }

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/70736.html