C# 读取保存App.config配置文件

  • 更新或新增[appSettings]节点的子节点值

        /// <summary>
        /// 更新或新增[appSettings]节点的子节点值,存在则更新子节点Value,不存在则新增子节点,返回成功与否布尔值
        /// </summary>
        /// <param name="configFileName">app.config路径</param>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <returns></returns>
        public static bool UpdateOrCreateAppSetting(string configFileName, string key, string value)
        {
            bool isSuccess = false;
            string filename = configFileName;

            //filename = System.Windows.Forms.Application.ExecutablePath + ".config";

            XmlDocument doc = new XmlDocument();
            doc.Load(filename); //加载配置文件

            XmlNode node = doc.SelectSingleNode("//appSettings");   //得到[appSettings]节点

            try
            {
                ////得到[appSettings]节点中关于Key的子节点
                XmlElement element = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");

                if (element != null)
                {
                    //存在则更新子节点Value
                    element.SetAttribute("value", value);
                }
                else
                {
                    //不存在则新增子节点
                    XmlElement subElement = doc.CreateElement("add");
                    subElement.SetAttribute("key", key);
                    subElement.SetAttribute("value", value);
                    node.AppendChild(subElement);
                }

                //保存至配置文件(方式一)
                using (XmlTextWriter xmlwriter = new XmlTextWriter(filename, null))
                {
                    xmlwriter.Formatting = Formatting.Indented;
                    doc.WriteTo(xmlwriter);
                    xmlwriter.Flush();
                }
                ////保存至配置文件(方式二)
                //doc.Save(filename);

                isSuccess = true;
            }
            catch (Exception e)
            {
                isSuccess = false;
                //输出的调试字符串
                string strOuput = string.Format("更新或新增[appSettings]节点的子节点值失败:{0}\n", e.Message);
                MessageBox.Show(strOuput);
            }

            return isSuccess;
        }
  • 删除[appSettings]节点中包含Key值的子节点
        /// <summary>
        /// 删除[appSettings]节点中包含Key值的子节点,返回成功与否布尔值
        /// </summary>
        /// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
        /// <param name="key">要删除的子节点Key值</param>
        /// <returns>返回成功与否布尔值</returns>
        public static bool DeleteByKey(string configFileName, string key)
        {
            bool isSuccess = false;
            string filename = configFileName;
            XmlDocument doc = new XmlDocument();
            doc.Load(filename); //加载配置文件

            XmlNode node = doc.SelectSingleNode("//appSettings");   //得到[appSettings]节点

            ////得到[appSettings]节点中关于Key的子节点
            XmlElement element = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");

            if (element != null)
            {
                //存在则删除子节点
                element.ParentNode.RemoveChild(element);
            }
            else
            {
                //不存在
            }

            try
            {
                //保存至配置文件(方式一)
                using (XmlTextWriter xmlwriter = new XmlTextWriter(filename, null))
                {
                    xmlwriter.Formatting = Formatting.Indented;
                    doc.WriteTo(xmlwriter);
                    xmlwriter.Flush();
                }

                isSuccess = true;
            }
            catch (Exception e)
            {
                //输出的调试字符串
                string strOuput = string.Format("删除[appSettings]节点中包含Key:{0}值的子节点失败:{1}\n", key, e.Message);
                MessageBox.Show(strOuput);
            }

            return isSuccess;
        }
  •  依据[appSettings]节点中的Key值获取value值
        /// <summary>
        ///依据app.config中的Key获取value
        /// </summary>
        /// <param name="configPath">配置文件路径</param>
        /// <returns></returns>
        private static string GetAppConfig(string configPath,string key)
        {
            var doc = new System.Xml.XmlDocument();
            doc.Load(configPath);

            //找出名称为“add”的所有元素  
            var nodes = doc.GetElementsByTagName("add");
            for (int i = 0; i < nodes.Count; i++)
            {
                //获得将当前元素的key属性  
                var xmlAttributeCollection = nodes[i].Attributes;
                if (xmlAttributeCollection != null)
                {
                    var att = xmlAttributeCollection["key"];
                    if (att == null) continue;
                    //根据元素的第一个属性来判断当前的元素是不是目标元素  
                    if (att.Value != key) continue; 
                    att = xmlAttributeCollection["value"];
                    return att.Value;
                }
                break;
            }
            return "";
        }

参考链接:https://blog.csdn.net/wzk456/article/details/49001391

发布了31 篇原创文章 · 获赞 2 · 访问量 2571

猜你喜欢

转载自blog.csdn.net/fangyu723/article/details/94618596
今日推荐