由于修改默认的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"); }
时间: 2024-10-10 19:12:53