首页  ·  知识 ·  云计算
对web.config进行简单新增修改删除读取操作
佚名  http://hi.baidu.com/chinadaima/blog/  综合  编辑:dezai  图片来源:网络
因为要把程序中的重要参数想保存到config 里,看到圈子里已有公布的代码了,在此谢谢作者 作者及出处

因为要把程序中的重要参数想保存到config 里,看到圈子里已有公布的代码了,在此谢谢作者

作者及出处 http://singlepine.cnblogs.com/articles/293683.html


1.建立一个class,ReadWriteConfig.cs
using System;
using System.Configuration;
using System.Reflection;
using System.Web;
using System.Xml;
public enum ConfigFileType
{
WebConfig,
AppConfig
}

namespace WebApplication1
{
///


/// Summary description for ReadWriteConfig.
///

public class ReadWriteConfig
{  
   public string docName = String.Empty;
   private XmlNode node=null;   
   private int _configType;
   public int ConfigType
   {
    get{ return _configType; }
    set{ _configType=value; }
   }

   #region SetValue
   public bool SetValue(string key, string value)
   {
    XmlDocument cfgDoc = new XmlDocument();
    loadConfigDoc(cfgDoc);  
    // retrieve the appSettings node  
    node = cfgDoc.SelectSingleNode("//appSettings");     
    if( node == null )
    {
     throw new InvalidOperationException( "appSettings section not found");
    }    
    try
    {  
     // XPath select setting "add" element that contains this key      
     XmlElement addElem= (XmlElement)node.SelectSingleNode("//add[@key='" +key +"']") ;
     if(addElem!=null)
     {
      addElem.SetAttribute("value",value);
     }   
     // not found, so we need to add the element, key and value  
     else
     {
      XmlElement entry = cfgDoc.CreateElement("add");
      entry.SetAttribute("key",key);   
      entry.SetAttribute("value",value);   
      node.AppendChild(entry);
     }  
     //save it  
     saveConfigDoc(cfgDoc,docName);  
     return true;
    }
    catch
    {
     return false;
    }
   }
       
   #endregion

   #region saveConfigDoc
   private void saveConfigDoc(XmlDocument cfgDoc,string cfgDocPath)
   {
    try
    {
     XmlTextWriter writer = new XmlTextWriter( cfgDocPath , null );
     writer.Formatting = Formatting.Indented;   
     cfgDoc.WriteTo( writer );   
     writer.Flush();
     writer.Close();
     return;
    }
    catch
    {
     throw;
    }
   }
       
   #endregion

   #region removeElement
   public bool removeElement (string elementKey)
   {
    try
    {  
     XmlDocument cfgDoc = new XmlDocument();
     loadConfigDoc(cfgDoc);
     // retrieve the appSettings node
     node = cfgDoc.SelectSingleNode("//appSettings");  
     if( node == null )
     {
      throw new InvalidOperationException( "appSettings section not found");
     }    
     // XPath select setting "add" element that contains this key to remove     
     node.RemoveChild( node.SelectSingleNode("//add[@key='" +elementKey +"']") );
     saveConfigDoc(cfgDoc,docName);
     return true;
    }
    catch
    {
     return false;
    }
   }       
   #endregion

   #region modifyElement
   public bool modifyElement (string elementKey)
   {
    try
    {  
     XmlDocument cfgDoc = new XmlDocument();
     loadConfigDoc(cfgDoc);
     // retrieve the appSettings node
     node = cfgDoc.SelectSingleNode("//appSettings");  
     if( node == null )
     {
      throw new InvalidOperationException( "appSettings section not found");
     }    
     // XPath select setting "add" element that contains this key to remove     
     node.RemoveChild(node.SelectSingleNode("//add[@key='" +elementKey +"']"));
     saveConfigDoc(cfgDoc,docName);
     return true;
    }
    catch
    {
     return false;
    }
   }       
   #endregion

   #region loadConfigDoc
   private XmlDocument loadConfigDoc( XmlDocument cfgDoc )
   {  
    // load the config file  
    if( Convert.ToInt32(ConfigType)==Convert.ToInt32(ConfigFileType.AppConfig))
    {
     docName= ((Assembly.GetEntryAssembly()).GetName()).Name;  
     docName +=   ".exe.config";
    }
    else
    {
     docName=HttpContext.Current.Server.MapPath("web.config");
    }
    cfgDoc.Load( docName );
    return cfgDoc;
   }
   #endregion
}
}
功能页面=================

WebForm1.aspx===

<%@ Page language="c#" Inherits="WebApplication1.WebForm1" CodeFile="WebForm1.aspx.cs" %>



   WebForm1
  
  
  
   http://schemas.microsoft.com/intellisense/ie5">


  
         Text="删除" onclick="Button1_Click">
         Text="新增" onclick="Button2_Click">
    key
   
    value
   
         Text="修改" onclick="Button3_Click">
  

WebForm1.aspx.cs====

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace WebApplication1
{
///


/// Summary description for WebForm1.
///

public partial class WebForm1 : System.Web.UI.Page
{

   protected void Page_Load(object sender, System.EventArgs e)
   {
   
   }

   #region Web Form Designer generated code
   override protected void OnInit(EventArgs e)
   {
    //
    // CODEGEN: This call is required by the ASP.NET Web Form Designer.
    //
    InitializeComponent();
    base.OnInit(e);
   }
  
   ///


   /// Required method for Designer support - do not modify
   /// the contents of this method with the code editor.
   ///

   private void InitializeComponent()
   {   

   }
   #endregion

   protected void Button2_Click(object sender, System.EventArgs e)
   {
    //新增
    ReadWriteConfig config = new ReadWriteConfig();  
    config.ConfigType = (int)ConfigFileType.WebConfig;
    config.SetValue(this.TextBox1.Text,this.TextBox2.Text);
   }

   protected void Button1_Click(object sender, System.EventArgs e)
   {
    //删除
    ReadWriteConfig config = new ReadWriteConfig();  
    config.ConfigType = (int)ConfigFileType.WebConfig;
    config.removeElement(this.TextBox1.Text);
   }

   protected void Button3_Click(object sender, System.EventArgs e)
   {
    //修改
    ReadWriteConfig config = new ReadWriteConfig();  
    config.ConfigType = (int)ConfigFileType.WebConfig;
    config.SetValue(this.TextBox1.Text,this.TextBox2.Text);
   }
}
}

PS :这里的新增 修改删除 只是对自带节点appSettings,修改,只能一个名称一个value 不灵活,因为config 虽然是xml 但不同于普通的xml不能随便加节点,要写个cs文件 并且声明,下次写个在config中自定义节点的!

虽然把程序中的重要参数放到config 里是保险的,但注意的是,config不同于其他文件,是程序配置文件,修改时主要权限!修改后 程序会重新装载编译,当前程序会话缓存会清空!程序需要重新登陆

本文作者:佚名 来源:http://hi.baidu.com/chinadaima/blog/
CIO之家 www.ciozj.com 微信公众号:imciow
   
免责声明:本站转载此文章旨在分享信息,不代表对其内容的完全认同。文章来源已尽可能注明,若涉及版权问题,请及时与我们联系,我们将积极配合处理。同时,我们无法对文章内容的真实性、准确性及完整性进行完全保证,对于因文章内容而产生的任何后果,本账号不承担法律责任。转载仅出于传播目的,读者应自行对内容进行核实与判断。请谨慎参考文章信息,一切责任由读者自行承担。
延伸阅读