CSDN首页 空间 新闻 论坛 Blog 下载 读书 网摘 搜索 .NET Java 视频 接项目 求职 在线学习 买书 程序员 通知
IBM Rational 系统开发最佳实践工具包 WebSphere MQ 最佳实践 TOP 15
CSDN社区
搜索 收藏 打印 关闭
CSDN社区 >  .NET技术 >  C#

请问如何读取web.config中自定义的信息。

楼主binapex(爱我不会错)2006-03-08 10:38:40 在 .NET技术 / C# 提问

例如:  
  <?xml   version="1.0"?>  
  <configuration>  
        <databases>  
              <database   name="testDB"   connectionString="testConn"   />  
        </databases>  
  </configuration> 问题点数:20、回复次数:17Top

1 楼c_delight(向前冲)回复于 2006-03-08 10:42:29 得分 1

<?xml   version="1.0"   encoding="utf-8"   ?>  
  <configuration>  
  <appSettings>  
  <add   key="assembly"   value="DataAccessApplicationBlock"></add>  
  </appSettings>  
  </configuration>  
  这样可以直接用ConfigurationSettings.AppSettings["testDB"];来读取Top

2 楼wangzhenyun_512(explorer)回复于 2006-03-08 10:44:35 得分 1

<appSettings>  
  <add   key="cConn"   value="server=.;database=aaa;uid=sa;pwd="   />  
  </appSettings>  
  用System.Configuration.ConfigurationSettings.AppSettings["cConn"]读取Top

3 楼xinyangt(信仰t)回复于 2006-03-08 10:57:58 得分 1

只要是在appSettings中设顶就ok了  
  <appSettings>  
  <add   key="Name"   value="testDB"   />  
  <add   key="connectionString"   value="testConn"   />  
  <add   key="Other"   value="Otherstring"   />  
  </appSettings>  
   
  在程序中用  
  s1   =   System.Configuration.ConfigurationSettings.AppSettings["Name"]  
  s2   =   System.Configuration.ConfigurationSettings.AppSettings["connectionString"]  
  s3   =   System.Configuration.ConfigurationSettings.AppSettings["Other"]  
  就可以读出刚才设置的字符串了Top

4 楼binapex(爱我不会错)回复于 2006-03-08 11:12:13 得分 0

因为特别的需要,我需要自定义配置,所以不能这样设置。Top

5 楼YAOHE(吆喝)回复于 2006-03-08 11:39:13 得分 1

读取XML文件,简单,DataSet都可以搞定,DataSet.ReadXml,读入数据后,就像操作数据表一样,取其中的内容Top

6 楼idda(碗掉了,头大个疤)回复于 2006-03-08 11:45:26 得分 2

呵呵,给你个例子,稍微改改,自定义的,默认的都可以读出来  
   
  public   static   string   GetConnString()   {  
  string   connString   =   string.Empty;  
  try   {  
  AppSettingsReader   configurationAppSettings   =   new   AppSettingsReader();  
  connString   =   ((string)(configurationAppSettings.GetValue("sqlConnection1.ConnectionString",   typeof(string))));  
   
  }   catch(Exception)   {  
  connString   =   null;  
  }  
   
  if(connString   ==   null   ||   connString   ==   string.Empty)   {  
  string   path   =   System.Reflection.Assembly.GetExecutingAssembly().Location;  
   
  path   =   path.Substring(0,   path.LastIndexOf("\\"))   +   "\\BPAdminTool.exe.config";  
   
  XmlDocument   doc   =   new   XmlDocument();  
  doc.Load(path);  
  XmlNode   root   =   doc.DocumentElement;  
  XmlNode   typeNode   =   root.SelectSingleNode("/configuration/appSettings/add[@key='sqlConnection1.ConnectionString']");  
   
  connString   =   typeNode.Attributes["value"].InnerText;  
  }  
   
  return   connString;  
  }Top

7 楼binapex(爱我不会错)回复于 2006-03-08 12:57:33 得分 0

没有更简单的吗,直接读取的?Top

8 楼adpost(ADPOST)回复于 2006-03-08 13:09:53 得分 0

我写了一个类,要以读写   Web.config   的内容Top

9 楼adpost(ADPOST)回复于 2006-03-08 13:10:43 得分 2

类的内容  
  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";  
  }  
   
   
  }  
  }Top

10 楼binapex(爱我不会错)回复于 2006-03-08 13:17:57 得分 0

呵呵,越搞越复杂,不过还是非常感谢上面的朋友。  
  只是我想找到一个最简单的Top

11 楼adpost(ADPOST)回复于 2006-03-08 17:38:42 得分 7

简单的方法:  
  如果采用自定义节点就把   appSettings改成成你自定义的节点  
  NameValueCollection   arrName   =   (NameValueCollection)ConfigurationSettings.GetConfig("appSettings");  
  if(arrName[name]   ==   null   ||   arrName[name]   ==   "")  
  {  
  return   extText;  
  }  
  else{  
  return   arrName[name];  
  }Top

12 楼adpost(ADPOST)回复于 2006-03-08 17:41:10 得分 0

忘了加说明了。  
  name   是你的   key  
  完整的过程  
  //取得配置文件数据内容  
  public   static   string   get_Setting(string   name,string   extText)  
  {  
  /*  
    *   如果直接用appSettings可以用   ConfigurationSettings.AppSettings["ConnStr"].ToString()直接读取,自定义   section可以把下面的   appSettings改成你自定义的section   name  
    */  
  NameValueCollection   arrName   =   (NameValueCollection)ConfigurationSettings.GetConfig("appSettings");  
  if(arrName[name]   ==   null   ||   arrName[name]   ==   "")  
  {  
  return   extText;  
  }  
  else{  
  return   arrName[name];  
  }  
   
  }Top

13 楼Samen168(Code to coding)回复于 2006-03-08 19:05:02 得分 4

可以创建自定义配置节,让应用程序在运行时读取。将配置节信息分组,置于配置文件的两个主要区域:配置节声明区域和配置节设置区域。将配置节声明置于   <configSections>   元素中。在   <configSections>   元素内的   <section>   元素中声明新配置节,即可创建新配置节。<section>   元素有两个属性:    
  name   属性,它是元素的名称,该元素包含节处理程序读取的信息。    
  type   属性,它是类的名称,该类读取信息。    
  配置设置的语法取决于与配置节关联的节处理程序。有关更多信息,请参见配置节架构。  
  下面的示例说明如何声明自定义节,该节使用   SingleTagSectionHandler   类。  
  <configuration>  
          <configSections>  
                  <section   name="sampleSection"  
                                    type="System.Configuration.SingleTagSectionHandler"   />  
          </configSections>  
   
          <sampleSection   setting1="Value1"   setting2="value   two"    
                                        setting3="third   value"   />  
  </configuration>  
  访问自定义配置节  
  可以使用静态方法   System.Configuration.ConfigurationSettings.GetConfig   来从应用程序访问配置设置。实现   System.Configuration.IConfigurationSectionHandler   的类计算   GetConfig   方法返回的设置。由于   IConfigurationSectionHandler.Create   方法的返回值是   Object   类型,所以必须将对象强制转换为节处理程序创建的类型。  
  若要从   sampleSection   读取设置,请将   ConfigurationSettings.GetConfig   返回的对象强制转换为   IDictionary   对象。  
  下面的代码说明如何从配置文件中检索设置。  
   
  [C#]  
  using   System;  
  using   System.Collections;  
  using   System.Configuration;  
   
  class   MyConfigurationReader   {  
     
          public   void   ReadMySettings()   {  
                  IDictionary   sampleTable   =   (IDictionary)    
                          ConfigurationSettings.GetConfig("sampleSection");  
                  string   value1   =   (string)sampleTable["setting1"];  
                  string   value2   =   (string)sampleTable["setting2"];  
                  string   value3   =   (string)sampleTable["setting3"];  
          }  
  }  
  Top

14 楼Samen168(Code to coding)回复于 2006-03-08 19:07:18 得分 0

MSDN里有的,楼主问之前查查相关资料吧Top

15 楼bbbbcccc()回复于 2006-03-09 11:36:58 得分 1

http://valenhua.go3.icpcn.com/Top

16 楼binapex(爱我不会错)回复于 2006-03-09 14:17:16 得分 0

呵呵,谢谢了。  
  虽然还没有能直接解决问题,但是离我的要求也不远了。Top

17 楼dfkjewyoldfjkleoe()回复于 2006-03-09 22:47:57 得分 0

www.source520.com           免费免注册80G源码书籍下载Top

相关问题

  • web用户自定义控件 如何自定义属性?
  • viewstate的值怎么在自定义类中读取?
  • 如何读取自定义XML配置文件?
  • 问关于读取自定义配置文件的问题!
  • 如何读取web.config的配置(不是自定义的app)
  • web自定义控件的问题
  • 关于web自定义控件
  • 自定义web登录问题
  • 自定义Web控件问题!!!
  • 如何在自定义方法中读取web.config中的配置内容?

关键词

  • 节点
  • 文件
  • 自定义
  • 配置
  • 配置文件
  • sectionname
  • 读取
  • arrname
  • cfgval
  • cfgname

得分解答快速导航

  • 帖主:binapex
  • c_delight
  • wangzhenyun_512
  • xinyangt
  • YAOHE
  • idda
  • adpost
  • adpost
  • Samen168
  • bbbbcccc

相关链接

  • CSDN .NET频道
  • .NET类图书
  • C#类图书
  • .NET类源码下载

广告也精彩

反馈

请通过下述方式给我们反馈
反馈
提问
网站简介|广告服务|VIP资费标准|银行汇款帐号|网站地图|帮助|联系方式|诚聘英才|English|问题报告
北京创新乐知广告有限公司 版权所有, 京 ICP 证 070598 号
世纪乐知(北京)网络技术有限公司 提供技术支持
Copyright © 2000-2008, CSDN.NET, All Rights Reserved
GongshangLogo