首页 > Windows开发 > 详细

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

时间:2015-06-18 14:49:07      阅读:321      评论:0      收藏:0      [点我收藏+]

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

 

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

原文:http://www.cnblogs.com/splashbrother/p/4585623.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!