惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
The GitHub Blog
The GitHub Blog
B
Blog
小众软件
小众软件
Jina AI
Jina AI
WordPress大学
WordPress大学
V
V2EX
MongoDB | Blog
MongoDB | Blog
Blog — PlanetScale
Blog — PlanetScale
P
Proofpoint News Feed
Y
Y Combinator Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
人人都是产品经理
人人都是产品经理
Microsoft Azure Blog
Microsoft Azure Blog
aimingoo的专栏
aimingoo的专栏
C
CERT Recently Published Vulnerability Notes
C
Cisco Blogs
Project Zero
Project Zero
云风的 BLOG
云风的 BLOG
K
Kaspersky official blog
Google DeepMind News
Google DeepMind News
宝玉的分享
宝玉的分享
T
Threat Research - Cisco Blogs
S
Securelist
V
Vulnerabilities – Threatpost
雷峰网
雷峰网
F
Fortinet All Blogs
D
DataBreaches.Net
I
Intezer
D
Docker
The Hacker News
The Hacker News
The Last Watchdog
The Last Watchdog
SecWiki News
SecWiki News
MyScale Blog
MyScale Blog
腾讯CDC
博客园_首页
Martin Fowler
Martin Fowler
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Application and Cybersecurity Blog
Application and Cybersecurity Blog
H
Help Net Security
GbyAI
GbyAI
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
L
Lohrmann on Cybersecurity
I
InfoQ
H
Hacker News: Front Page
T
Threatpost
Stack Overflow Blog
Stack Overflow Blog
博客园 - 叶小钗
T
Troy Hunt's Blog
Microsoft Security Blog
Microsoft Security Blog

博客园 - 暮江独钓

无数据库日志文件恢复数据库方法两则[转自www.sql2005.com.cn] Use ToString() to format values C# Tostring() 格式大全 [转] - 暮江独钓 C#数值结果表(格式化字符串) - 暮江独钓 - 博客园 T-SQL循环打印一年中所有的日期(WHILE循环) SQL Server各种日期计算方法(收藏) ado.net 如何读取 excel (转贴) C#编码标准--编码习惯 发布一个很COOL的图片验证码程序[含源码](转) 怎么在框架窗口中退出 c#取机器码 [转] VS2005如果使用Forms驗證,Login頁面不能引用工程中CSS和IMG文件解決方案 [转] ASP.NET几种安全验证方法[转] 最近一直在做C#操作office方面的工作!总结一下!Word(二) [转] 使用C#自动生成Word2003文档(通过操作COM组件实现) [转] ASP.NET在线用户列表精确版——解决用户意外退出在线列表无法及时更新问题 Cookie与自动保存 [ASP.NET] 如何在GridView中使用DataFromatString DataFormatString格式字符串
C#中对Web.config配置文件的操作(增删改读) [转]
暮江独钓 · 2007-08-17 · via 博客园 - 暮江独钓

C#中对Web.config配置文件的操作(增删改读)

using System;
using System.Configuration;
using System.Reflection;
using System.Web;
using System.Xml;
public enum ConfigFileType
{
 WebConfig,
 AppConfig
}

namespace ConfigRW
{
 /// <summary>
 /// Summary description for ReadWriteConfig.
 /// </summary>
 public class ReadWriteConfig
 {  
  public string docName = String.Empty;
  private XmlNode node=null;   
  private int _configType;
  public string message;
  public int ConfigType
  {
   get{ return _configType; }
   set{ _configType=value; }
  } 

  #region GetValue
  public string GetValue( string key )
  {   //读取
   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     
    XmlElement addElem= (XmlElement)node.SelectSingleNode("//add[@key='" +key +"']") ;
    if(addElem == null)
    {
     message = "此key不存在!";
     return message;
    }
    message = System.Configuration.ConfigurationSettings.AppSettings[key];
    return message;
   }
   catch
   {
    message = "操作异常,获取value值失败!";
    return message;
   }
  }
  #endregion

  #region SetValue
  public string 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)
    {
     message = "此key已经存在!";
     return message;
    }   
    // 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);  
    message = "添加成功!";
    return message;
   } 
   catch
   {
    message = "操作异常,添加失败!";
    return message;
   }
  } 
       
  #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 string 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");
    } 
  
    XmlElement addElem= (XmlElement)node.SelectSingleNode("//add[@key='" +elementKey +"']") ;
    if(addElem == null)
    {     
     message = "此key不存在!";
     return message;
    }   
    // XPath select setting "add" element that contains this key to remove     
    node.RemoveChild( node.SelectSingleNode("//add[@key='" +elementKey +"']") );
    saveConfigDoc(cfgDoc,docName); 
    message = "删除成功!";
    return message;
   }
   catch
   {
    message = "操作异常,删除失败!";
    return message;
   }
  }       
  #endregion

  #region modifyElement
  public string modifyElement (string elementKey, string elementValue)
  { //修改
   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     
    XmlElement addElem= (XmlElement)node.SelectSingleNode("//add[@key='" +elementKey +"']") ;
    if(addElem == null)
    {
     message = "此key不存在!";
     return message;
    }
    
    addElem.SetAttribute("value",elementValue);
    //save it  
    saveConfigDoc(cfgDoc,docName);
    message = "修改成功!";
    return message;
   }
   catch
   {
    message = "操作异常,修改失败!";
    return message;
   }
  }       
  #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
 }
}

测试页面

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 ConfigRW
{
 /// <summary>
 /// Summary description for WebForm1.
 /// </summary>
 public class WebForm1 : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.Button Button1;
  protected System.Web.UI.WebControls.Label Label1;
  protected System.Web.UI.WebControls.TextBox TextBox1;
  protected System.Web.UI.WebControls.Label Label2;
  protected System.Web.UI.WebControls.TextBox TextBox2;
  protected System.Web.UI.WebControls.Button Button3;
  protected System.Web.UI.WebControls.Button Button4;
  protected System.Web.UI.WebControls.Button Button2;
 
  private 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);
  }
  
  /// <summary>
  /// Required method for Designer support - do not modify
  /// the contents of this method with the code editor.
  /// </summary>
  private void InitializeComponent()
  {   
   this.Button1.Click += new System.EventHandler(this.Button1_Click);
   this.Button2.Click += new System.EventHandler(this.Button2_Click);
   this.Button3.Click += new System.EventHandler(this.Button3_Click);
   this.Button4.Click += new System.EventHandler(this.Button4_Click);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion

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

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

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

  private void Button4_Click(object sender, System.EventArgs e)
  {
   //读取
   ReadWriteConfig config = new ReadWriteConfig();  
   config.ConfigType = (int)ConfigFileType.WebConfig;
   this.TextBox2.Text = config.GetValue(this.TextBox1.Text);
  }
 }
}