官方热线:0769-22501808

7x24热线:+86 13310811808

© 2012-2015 宏翔科技 版权所有

Web.Config文件修改

宏翔软件技术文章2021/2/23 15:33:04

第一个方法自动删除原有注释

     Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
            AppSettingsSection app = config.AppSettings;
            app.Settings["Wechat_Pay_LogLevel"].Value = this.txt_Wechat_Pay_LogLevel.Value.ToString();
            app.Settings["TestOpenID"].Value = this.txt_TestOpenID.Value.ToString();
            app.Settings["Wechat_JsApiPay_NotifyUrl"].Value = this.txt_Wechat_JsApiPay_NotifyUrl.Value.ToString();
            app.Settings["OAuthScope"].Value = this.txt_OAuthScope.Value.ToString();

            config.Save(ConfigurationSaveMode.Modified);

第二个方法保留原有注释

public void SaveAppSettingsMethod(string key, string value)
    {
        string configPath = this.Server.MapPath("~/web.config");
        System.Xml.XmlDocument xml = new System.Xml.XmlDocument();
        xml.Load(configPath);
        System.Xml.XmlNodeList nodeList = xml.GetElementsByTagName("appSettings");
        if (nodeList != null)
        {
            if (nodeList.Count >= 1)
            {
                System.Xml.XmlNode node = nodeList[0];
                foreach (System.Xml.XmlNode item in node)
                {
                    if (item.NodeType == System.Xml.XmlNodeType.Comment)
                    {
                        continue;
                    }
                    System.Xml.XmlAttribute xaKey = item.Attributes["key"];
                    System.Xml.XmlAttribute xaValue = item.Attributes["value"];
                    if (xaKey.Value.Equals(key))
                    {
                        xaValue.Value = value;
                    }
                }
            }
        }
        xml.Save(configPath);
    }