粗茶淡饭


Rome was not built in a day. 生气是拿别人的错误来惩罚自己
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

操作Web.config的AppSettings

Posted on 2008-10-30 13:13  茶^_^米  阅读(267)  评论(0编辑  收藏  举报


操作Web.config的AppSettings
/// <summary>
        /// 操作Xml的AppSettings
        /// </summary>
        /// <param name="webConfigPath"></param>
        /// <param name="AppsettingsAddKey"></param>
        /// <param name="KeyValue"></param>
        /// <returns></returns>
        public static bool AppSettingsEdit(string webConfigPath, string AppsettingsAddKey, string KeyValue)
        {
            try
            {
                string path = System.Web.HttpContext.Current.Server.MapPath(webConfigPath + "/web.config");
                XmlDocument xd = new XmlDocument();
                xd.Load(path);
                //如果没有appsetting,则添加
                if (xd.SelectNodes("//appSettings").Count == 0)
                {
                    xd.DocumentElement.AppendChild(xd.CreateElement("appSettings"));
                }
                //判断节点是否存在,如果存在则修改当前节点
                bool addnode = true;
                foreach (XmlNode xn1 in xd.SelectNodes("/configuration/appSettings/add"))
                {
                    if (xn1.Attributes["key"].Value == AppsettingsAddKey)
                    {
                        addnode = false;
                        xn1.Attributes["value"].Value = KeyValue;
                        //        xn1.parentnode.removechild(xn1);
                        break;
                    }
                }
                //当前节点不存在,则添加新节点
                if (addnode)
                {
                    //创建新节点
                    XmlNode xn2 = xd.CreateElement("add");
                    //添加key
                    XmlAttribute xa = xd.CreateAttribute("key");
                    xa.Value = AppsettingsAddKey;
                    xn2.Attributes.Append(xa);
                    //添加value
                    xa = xd.CreateAttribute("value");
                    xa.Value = KeyValue;
                    xn2.Attributes.Append(xa);
                    xd.SelectSingleNode("/configuration/appSettings").AppendChild(xn2);
                }
                //保存web.config
                xd.Save(path);
                return true;
            }
            catch
            {
                return false;
            }