C# 读写 Web.config 的类

webconfig详解 webconfig详解. 立即下载

可以自定义 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);
  }
 }
}


C#获取web.config配置文件内容的方法 本文实例讲述了C#获取web.config配置文件内容的方法。分享给大家供大家参考。具体实现方法如下: 1.ConfigurationManager提供对客户端应用程序配置文件的访问。 其有两个属性:ConnectionStrings 获取当前应用程序默认配置的 ConnectionStringsSection 数据。 方法一: 代码如下:string myConn =System.Configuration.ConfigurationManager.ConnectionStrings[“sqlConnectionString”].ConnectionString; 方法二: 代码如下:s 立即下载

相关推荐

Excel基金净值自动更新:手把手教你用Power Query抓取天天基金网数据(含常见错误修复)

本文详细介绍了如何利用Excel内置的Power Query工具,从天天基金网自动抓取基金净值数据,实现表格数据的自动刷新。通过手把手教程,您将学会构建参数化查询、整合多基金数据、计算持仓盈亏,并解决网页结构变动等常见错误,最终打造一个专属的、可自动更新的基金监控仪表盘,彻底告别手动更新。

xx56789的博客 747

c# 读写web.config

【代码】c# 读写web.config。

qq_38643387的博客 771

关于并网继电器的继电器自检逻辑及实现方式

对于常规的光伏并网逆变器来说,继电器控制至关重要。继电器一般位于逆变电感后,共模电感前,用于将逆变电压与电网电压脱开,一般国外有双继电器的安规强制认证要求,国内目前只需要单继电器要求(后续应该会有双继电器要求,个人感觉)

weixin_29982209的博客 2630

C#读取WebConfig

XmlTextReader reader = new XmlTextReader(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Web.config")); reader.MoveToContent(); XmlDocument configDoc = new XmlDocument(); configDoc.LoadXml(reader.ReadOuterX..

一杯浊酒笑风尘 1204

hive sql每个用户的累积访问次数

我们有如下的用户访问数据 userId visitDate visitCount u01 2017/1/21 5 u02 2017/1/23 6 u03 2017/1/22 8 u04 2017/1/20 3 u01 2017/1/23 6 u01 2017/2/21 8 U02 2017/1/23 6 U01 2017/2/22 4 要求使用SQL...

weixin_39150719的博客 3490

Windows安全中心空白问题修复:服务重置与系统组件修复实战指南

Windows系统服务是操作系统后台运行的核心组件,负责管理硬件资源、应用程序执行和系统功能。其稳定运行依赖于服务控制管理器、注册表配置和系统文件完整性。当关键服务(如Windows Update、安全中心服务)因更新失败、权限错误或组件损坏而无法正常启动时,依赖其功能的应用程序界面便会出现加载异常。在系统维护与故障排除领域,通过命令行工具重置服务状态、修复系统映像已成为工程师的必备技能。本文聚焦Windows安全中心界面空白这一典型故障,深入剖析其与Windows Update服务、组件存储损坏的关联,并

weixin_30859423的博客 436

C# 获取web.config配置文件内容

1.web.config提供对客户端应用程序配置文件的访问。 其有两个属性1.ConnectionStrings 获取当前应用程序默认配置的 ConnectionStringsSection 数据。 方法一: string sqlConString =System.Configuration.ConfigurationManager.ConnectionStrings[“sqlConStr”].ConnectionString; 方法二: string sqlConString =System.Web.Co

MrGuoXianSen的博客 3313

英飞凌TC397芯片时钟树详解:从EB-tresos配置到PLL锁相环实战避坑

本文详细解析了英飞凌TC397芯片的时钟树架构,从EB-tresos配置到PLL锁相环的实战应用,帮助工程师避免常见配置陷阱。文章深入探讨了时钟源层、频率转换层和分配网络层的设计原理,提供了PLL配置的数学公式和EB-tresos关键容器的配置要点,并分享了调试技巧与性能优化实践,适用于MCU开发中的时钟管理需求。

weixin_42524226的博客 214

C# 读写 Web.config

  FileName: ConfigManager  // Description: 静态方法业务类,用于对C#、ASP.NET中的WinForm & WebForm 项目程序配置文件 // app.config和web.config的[appSettings]和[connectionStrings]节点进行新增、修改、删除和读取相关的操作。 using System;

李赛赛的专栏 1508

科研绘图系列:R语言折线图(linechart plots)

科研绘图系列:R语言折线图(linechart plots)

专注生信领域 1277

LVGL(lv_table)

LVGL中的lv_table是一个轻量级表格控件,用于显示行列式文本数据。它支持设置单元格内容/样式、行列调整、事件响应等基础功能,适用于参数配置、数据展示等场景。通过API可快速创建表格,设置行列数、填充数据,并自定义对齐方式与样式。但需注意默认无滚动条、行数限制等问题。该控件适合简单表格需求,复杂交互需结合自定义事件处理。

m0_49476241的博客 1283

C# ConfigurationManager类[读写app.config|Web.config]

注重应用ConfigurationManager类主要应用于读写配置文件app.config|Web.config配置文件可以存储连接数据库字符串、接口路径、一些账套字符串等等他就像JAVA里的application.properties 要用存读取配置文件里的信息在config中,我们主要存储这两类Uid=123;pwd=123"/>

可达鸭的博客 1512

【YOLO多模态检测顶刊】TGRS 2025范文解读,RGFNet 可见光-红外图像融合目标检测,2026年基于YOLO多模态融合属于发文热点,小论文和大论文通用,通读顶刊了解做实验和论文写作的全流程

🔥本文提出了一种反射率引导的渐进特征对齐网络(RGFNet)用于全天候无人机目标检测。该方法利用Retinex理论从可见光图像中提取光照不变的反射率特征,设计了反射率引导协同对齐模块(RCAM)实现跨模态双向特征对齐,并通过光照感知选择性融合模块(LSFM)在共享状态空间中进行高效特征交互。在DroneVehicle和DVTOD数据集上的实验表明,RGFNet分别达到81.4%和88.5%的mAP,显著优于现有方法。该方法有效解决了低光照条件下可见光-红外图像特征错位问题,为全天候无人机检测提供了新思路。

Ai缝合怪、助力小伙伴高效发论文 1093

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.Com

189

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

适用于app.config与web.config的ConfigUtil读写工具类 基于MongoDb官方C#驱动封装MongoDbCsharpHelper类(CRUD类) 基于ASP.NE...

适用于app.config与web.config的ConfigUtil读写工具类 之前文章:《两种读写配置文件的方案(app.config与web.config通用)》,现在重新整理一个更完善的版本,增加批量读写以及指定配置文件路径,代码如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15...

701

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

[转]对web.config进行新增修改删除读取操作

1.建立一个class,ReadWriteConfig.cs usingSystem;usingSystem.Configuration;usingSystem.Reflection;usingSystem.Web;usingSystem.Xml;publicenumConfigFileType{WebConfig,AppConfig}namespace...

dianmu2198的博客 141

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

对web.config进行新增修改删除读取操作

1.建立一个class,ReadWriteConfig.cs usingSystem; usingSystem.Configuration; usingSystem.Reflection; usingSystem.Web; usingSystem.Xml; publicenumConfigFileType { WebConfig, AppConf...

weixin_34051201的博客 123

ASP.NET Web.Config 读写辅助类

using System; using System.Configuration; using System.Web; using System.Web.Configuration; namespace Whir.ezEIP { /// /// WebConfig读写辅助类 /// public class WebConfigManager : IDispos

清山博客 3866

c# ef框架 mysql_C#简单构架之EF进行读写分离+多数据库(Mysql/SqlService)

最近因为项目需要,研究了下EF的读写分离,所以做了一个demo进行测试,下面是项目的结构表现层view主要提供Web、WebApi等表现层的解决方案公共层public主要提供项目公共类库,数据缓存基础方法等实体层model主要提供数据库映射模型,还有就是DDD领域操作模型数据层Db主要封装EF操作基础类数据服务层Service主要提供数据库操作服务、缓存操作服务数据接口服务层inface主要提供数...

weixin_42647395的博客 526

c#mysql+读取_C#简单构架之EF进行读写分离+多数据库(MYSQL\/SQLSERVICE)

(点击上方蓝字,可快速关注我们)来源:追随微笑nblogs.com/kq123321/p/7002054.html最近因为项目需要,研究了下EF的读写分离,所以做了一个demo进行测试,下面是项目的结构 表现层view主要提供Web、WebApi等表现层的解决方案公共层public主要提供项目公共类库,数据缓存基础方法等实体层model主要提供数据库映射模型,还有就是DDD领域操作模型数据层Db主...

weixin_29363945的博客 384

博客目录 分类: 其他 2014-07-16 22:...

C# 01.C# SMTP邮件发送02.利用YaHoo YUI实现Javascript CSS 压缩03.IIS日志分析工具04.C# Winform 文件编码批量转换工具05.C# Winform ListView使用06.DbHelper-SQL数据库访问助手07.FileHelper-文件操作辅助类08.AppPoolService-IIS应用程序池辅助类(...

weixin_34220963的博客 389

.net面试题系列文章十(附答案)

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_34240520的博客 86

C#—读写web.config

asp.net2.0新添加了对web.config直接操作的功能。开发的时候有可能用到在web.config里设置配置文件,其实是可以通过程序来设置这些配置节的。 1.首先先引用名称空间: using System.Web.Configuration; web.config里的配置节: <appSettings> <addkey="practic...

weixin_30685029的博客 219

C#读写app.config中的数据

读语句:           String str = ConfigurationManager.AppSettings["DemoKey"]; 写语句:            Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);            cfa.

风之&诉 4441
上一篇: IIS配置管理在线教程设置全攻略
下一篇: 在.net中读写ORACLE LOB 对象
adpost
博客等级 码龄23年 1粉丝 3原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值