所谓的潇洒

导航

读写其他程序的config文件

  当你编写的Web程序或者Windows服务需要修改配置文件才能正常使用时,用户(谁知道是不是用户说的,(¬︿̫̿¬☆))希望用一个带界面的程序来修改配置文件(什么,你有话说?好了,我知道你想说什么,我也是)。这时肯定会想到用ConfigrationManager来实现,但是试下就发现,其他程序的配置内容访问受限,也就是写不了。那只能用文件读写了,我们知道config文件内容其实是xml格式,所以方案出来了:

   /// <summary>
    /// 其他程序config文件的Appsetting读写
    /// </summary>
    public class OutConfigHelper
    {
        XmlDocument _doc = new XmlDocument();
        XmlNode _appSettingNode;
        string _configName = string.Empty;
        public OutConfigHelper(string configFile)
        {
            try
            {
                _configName = configFile;
                _doc.Load(configFile);
                foreach (XmlNode node in _doc.ChildNodes)
                {
                    if (node.Name.Equals("configuration", StringComparison.OrdinalIgnoreCase))
                    {
                        foreach (XmlNode cNode in node.ChildNodes)
                        {
                            if (cNode.Name.Equals("appSettings", StringComparison.OrdinalIgnoreCase))
                            {
                                _appSettingNode = cNode;
                                return;
                            }
                        }
                        return;
                    }
                }
            }
            catch { }
        }

        public string this[string key]
        {
            get
            {
                try
                {
                    if (_appSettingNode == null) return string.Empty;
                    foreach (XmlNode node in _appSettingNode.ChildNodes)
                    {
                        if (node.Name == "add" && node.Attributes["key"] != null && node.Attributes["value"] != null && node.Attributes["key"].Value == key)
                        {
                            return node.Attributes["value"].Value;
                        }
                    }
                }
                catch { }
                return string.Empty;
            }
            set
            {
                try
                {
                    if (_appSettingNode == null) return;
                    foreach (XmlNode node in _appSettingNode.ChildNodes)
                    {
                        if (node.Name == "add" && node.Attributes["key"] != null && node.Attributes["value"] != null && node.Attributes["key"].Value == key)
                        {
                            node.Attributes["value"].Value = value;
                            return;
                        }
                    }
                }
                catch { }
            }
        }

        public void Save()
        {
            _doc.Save(_configName);
        }
    }

调用说明:

  var config=new OutConfigHelper(@"路径\aa.exe.config");

  string value=config["userName"].Value;

  config["userName"].Value="aa";

  config.Save();

posted on 2019-10-14 20:52  所谓的潇洒  阅读(161)  评论(0编辑  收藏  举报