C# 读写 Web.config 的类

可以自定义 section也可直接用 appSettins这个节点
代码

using System;
using System.Xml;
using System.Collections;
using System.Collections.Specialized;
using System.Configuration;
using System.Reflection;
namespace Adpost.Comm.ConfigModel
{
 /// <summary>
 /// Web.config 操作类
 ///  Copyright (C) 2006-2008 adpost
 /// 定义为不可继承性
 /// </summary>
 public sealed class ConfigClass
 {
  public static string GetConfigString(string SectionName,string key)
  {
   if(SectionName==null || SectionName == "")
   {
    //try
    //{
     NameValueCollection cfgName = (NameValueCollection)ConfigurationSettings.GetConfig("appSettings");
     if(cfgName[key] == null || cfgName[key] == "")
     {
      throw (new Exception("在Web.config文件中未发现配置项: /"" + key.ToString() + "/""));
     }
     else
     {
      return cfgName[key];
     }
    /*}
    catch(NullReferenceException)
    {
     throw (new Exception("在Web.config文件中未发现配置项: /"" + key.ToString() + "/""));
    }*/
   }
   else{
    //try
    //{
     NameValueCollection cfgName = (NameValueCollection)ConfigurationSettings.GetConfig(SectionName);
     if(cfgName[key] == null || cfgName[key] == "")
     {
      throw (new Exception("在Web.config文件中未发现配置项: /"" + key.ToString() + "/""));
     }
     else
     {
      return cfgName[key];
     }
    /*}
    catch(NullReferenceException)
    {
     throw (new Exception("在Web.config文件中未发现配置项: /"" + key.ToString() + "/""));
    }*/
   }
   /*   
    直接返回的方法
   */
  }

  
  /// <summary>
  /// 得到配置文件中的配置decimal信息
  /// </summary>
  /// <param name="key"></param>
  /// <returns></returns>
  public static decimal GetConfigDecimal(string SectionName,string key)
  {
   decimal result = 0;
   string cfgVal = GetConfigString(SectionName,key);
   if(null != cfgVal && string.Empty != cfgVal)
   {
    //try
    //{
     result = decimal.Parse(cfgVal);
    /*}
    catch(FormatException)
    {
     // Ignore format exceptions.
    }*/
   }

   return result;
  }
  /// <summary>
  /// 得到配置文件中的配置int信息
  /// </summary>
  /// <param name="key"></param>
  /// <returns></returns>
  public static int GetConfigInt(string SectionName,string key)
  {
   int result = 0;
   string cfgVal = GetConfigString(SectionName,key);
   if(null != cfgVal && string.Empty != cfgVal)
   {
    //try
    //{
     result = Int32.Parse(cfgVal);
    /*}
    catch(FormatException)
    {
     // Ignore format exceptions.
    }*/
   }

   return result;
  }
  /// <summary>
  /// 写入配置文件
  /// </summary>
  /// <param name="SectionName">节点名称</param>
  /// <parma name="key">键名</param>
  /// <parma name="value">键值</param>
  public static void SetConfigKeyValue(string SectionName,string key,string value)
  {
   //导入配置文件
   XmlDocument doc = loadConfigDocument();
   //重新取得 节点名
   XmlNode node= doc.SelectSingleNode("//" + SectionName);
   if (node == null)
    throw new InvalidOperationException(SectionName + " section not found in config file.");

   try
   {
    // 用 'add'元件 格式化是否包含键名
    // select the 'add' element that contains the key
    XmlElement elem = (XmlElement)node.SelectSingleNode(string.Format("//add[@key='{0}']", key));

    if (elem != null)
    {
     //修改或添加键值
     elem.SetAttribute("value", value);
    }
    else
    {
     //如果没有发现键名则进行添加设置键名和键值
     elem = doc.CreateElement("add");
     elem.SetAttribute("key", key);
     elem.SetAttribute("value", value);
     node.AppendChild(elem);
    }
    doc.Save(getConfigFilePath());
   }
   catch
   {
    throw;
   }

  }
  public static void RemoveSectionKey(string SectionName,string key)
  {
   //导入配置文件
   XmlDocument doc = loadConfigDocument();

   //重新取得 节点名
   XmlNode node= doc.SelectSingleNode("//" + SectionName);

   try
   {
    if (node == null)
     throw new InvalidOperationException(SectionName + " section not found in config file.");
    else
    {
     // 用 'add' 方法格式 key和value
     node.RemoveChild(node.SelectSingleNode(string.Format("//add[@key='{0}']", key)));
     doc.Save(getConfigFilePath());
    }
   }
   catch (NullReferenceException e)
   {
    throw new Exception(string.Format("The key {0} does not exist.", key), e);
   }
  }

  /// <summary>
  /// 读入配置文件
  /// </summary>
  private static XmlDocument loadConfigDocument()
  {
   XmlDocument doc = null;
   try
   {
    doc = new XmlDocument();
    doc.Load(getConfigFilePath());
    return doc;
   }
   catch (System.IO.FileNotFoundException e)
   {
    throw new Exception("No configuration file found.", e);
   }
  }
  /// <summary>
  /// 取得置文件路径和名称
  /// </summary>
  private static string getConfigFilePath()
  {
   return AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
   //return Assembly.GetExecutingAssembly().Location + ".config";
  }

  
 }
}
示例:
Web.Config的配置


<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="usedCarSettings" type="System.Configuration.NameValueFileSectionHandler, System, Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  </configSections>
  <!--
 配置参数,修改网站配置请修改请配置文件-->
  <usedCarSettings>
    <add key="ConnStr" value="Provider=SQLOLEDB;User ID=sa; Password=; Initial Catalog=tozj;Data Source=(local);" />
    <!-- 文件上传路径和大小配置 File uploa floder and size setting  -->
    <add key="UploadFolder" value="D:/website/UploadPic" />
    <add key="MaxUploadSize" value="1000000" />
    <!-- 网站设置开关 website OPEN/OFF setting -->
    <!-- 网站数据表通用头 -->
    <add key="DataTableHead" value="AD_" />
    <!-- 网站是否生效,1;生效,0:关闭 -->
    <add key="SiteStat" value="1" />
    <!-- 用户是否必须注册 1:必须,2:不必注册,3:可注册也可不注册 -->
    <add key="Registerstat" value="1" />
    <!--
  Sql Server 日期格式化
  Format SQL Server expects the dates to be in
  This doesn't affect what user sees on web pages.
  -->
    <add key="SQLServerDateFormat" value="yyyy-MM-dd HH:mm:ss" />
  </usedCarSettings>
  <system.web>
    <compilation defaultLanguage="c#" debug="false" />
    <customErrors mode="RemoteOnly" />
    <authentication mode="Windows" />
    <authorization>
      <allow users="*" />
      <!-- 允许所有用户 -->
    </authorization>
    <trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true" />
    <sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes" cookieless="false" timeout="20" />
    <globalization requestEncoding="utf-8" responseEncoding="utf-8" />
  </system.web>
</configuration>

界面
<%@ Page language="c#" Codebehind="Default.aspx.cs" AutoEventWireup="false" Inherits="tozj.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
 <HEAD>
  <title>WebForm1</title>
  <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
  <meta content="C#" name="CODE_LANGUAGE">
  <meta content="JavaScript" name="vs_defaultClientScript">
  <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
 </HEAD>
 <body MS_POSITIONING="GridLayout">
  <form id="Form1" method="post" runat="server">
   <FONT face="宋体">
    <asp:label id="lblWarning" style="Z-INDEX: 101; LEFT: 248px; POSITION: absolute; TOP: 272px"
     runat="server" ForeColor="Red" Font-Size="Larger" Font-Bold="True" Height="64px" Width="256px"></asp:label>
    <asp:TextBox id="txtKey" style="Z-INDEX: 102; LEFT: 200px; POSITION: absolute; TOP: 96px" runat="server"></asp:TextBox>
    <asp:TextBox id="txtValue" style="Z-INDEX: 103; LEFT: 200px; POSITION: absolute; TOP: 136px"
     runat="server"></asp:TextBox>
    <asp:Button id="Button1" style="Z-INDEX: 104; LEFT: 208px; POSITION: absolute; TOP: 192px" runat="server"
     Text="添加"></asp:Button>
    <asp:Button id="Button2" style="Z-INDEX: 105; LEFT: 304px; POSITION: absolute; TOP: 192px" runat="server"
     Text="修改"></asp:Button>
    <asp:Button id="Button3" style="Z-INDEX: 106; LEFT: 384px; POSITION: absolute; TOP: 192px" runat="server"
     Text="删除"></asp:Button>
    <asp:Label id="Label1" style="Z-INDEX: 107; LEFT: 128px; POSITION: absolute; TOP: 104px" runat="server">键名</asp:Label>
    <asp:Label id="Label2" style="Z-INDEX: 108; LEFT: 128px; POSITION: absolute; TOP: 136px" runat="server">键值</asp:Label>
    <asp:TextBox id="txtSectionName" style="Z-INDEX: 109; LEFT: 200px; POSITION: absolute; TOP: 64px"
     runat="server">appSettings</asp:TextBox>
    <asp:Label id="Label3" style="Z-INDEX: 110; LEFT: 136px; POSITION: absolute; TOP: 72px" runat="server">节点</asp:Label></FONT></form>
 </body>
</HTML>

源文件


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;
using Adpost.Comm.ConfigModel;
namespace tozj
{
 /// <summary>
 /// WebForm1 的摘要说明。
 /// </summary>
 public class WebForm1 : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.TextBox txtKey;
  protected System.Web.UI.WebControls.TextBox txtValue;
  protected System.Web.UI.WebControls.Button Button1;
  protected System.Web.UI.WebControls.Button Button2;
  protected System.Web.UI.WebControls.Button Button3;
  protected System.Web.UI.WebControls.Label Label1;
  protected System.Web.UI.WebControls.Label Label2;
  protected System.Web.UI.WebControls.TextBox txtSectionName;
  protected System.Web.UI.WebControls.Label Label3;
  protected System.Web.UI.WebControls.Label lblWarning;
 
  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
   try
   {
    lblWarning.Text = ConfigClass.GetConfigString("usedCarSettings","ConnStr").ToString();
    // set the new value
   }
   catch(FormatException)
   {}
  }

  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </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.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion

  private void Button1_Click(object sender, System.EventArgs e)
  {
   string txtSectionName = this.txtSectionName.Text.ToString();
   string txtKey = this.txtKey.Text.ToString();
   string txtValue = this.txtValue.Text.ToString();
   ConfigClass.SetConfigKeyValue(txtSectionName,txtKey,txtValue);
  }

  private void Button2_Click(object sender, System.EventArgs e)
  {
   string txtSectionName = this.txtSectionName.Text.ToString();
   string txtKey = this.txtKey.Text.ToString();
   string txtValue = this.txtValue.Text.ToString();
   ConfigClass.SetConfigKeyValue(txtSectionName,txtKey,txtValue);
  }

  private void Button3_Click(object sender, System.EventArgs e)
  {
   string txtSectionName = this.txtSectionName.Text.ToString();
   string txtKey = this.txtKey.Text.ToString();
   ConfigClass.RemoveSectionKey(txtSectionName,txtKey);
  }
 }
}


  • 0
    点赞
  • 0
    收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页
评论 1

打赏作者

adpost

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值