当前位置:编程学习 > C#/ASP.NET >>

【急】C#怎么读取自定义web.config配置

--------------------编程问答-------------------- 调用,后redisConfig总是null

RedisConfig2 redisConfig = ConfigurationManager.GetSection("RedisConfig") as RedisConfig2;
                ReadRedis timeline = redisConfig.ReadRedisChildren["TimeLine"];
                return new RedisClient(timeline.Host, timeline.Port, timeline.Password);
--------------------编程问答-------------------- 简单点的用LinqToXml --------------------编程问答-------------------- 照着网上各种教程写的,照猫画虎,没整好,呵呵

引用 2 楼 nice_fish 的回复:
简单点的用LinqToXml
--------------------编程问答-------------------- ConfigurationManager.ConnectionStrings[name].ConnectionString;这样获取试试。 --------------------编程问答--------------------
引用 4 楼 qingfeng_wu 的回复:
ConfigurationManager.ConnectionStrings["namestr"].ConnectionString;这样获取试试。

主要,这样获取,配置文件要这样写:
<connectionStrings>
       <add name="namestr"
      connectionString="Data Source=.;Initial Catalog=jewelbo;Persist Security Info=True;User ID=sa;Password=123"
      providerName="System.Data.SqlClient" />
</connectionStrings>

请将jewelbo这个修改为你自己的数据库,用户名和密码也修改成自己的。 --------------------编程问答-------------------- 配置节点配置有问题吧

你应该配置<section>节点

配置节组是使用<sectionGroup>元素,将类似的配置节分到同一个组中。配置节组声明部分将创建配置节的包含元素,在<configSections>元素中声明配置节组,并将属于该组的节置于<sectionGroup>元素中。下面是一个包含配置节组的配置文件的例子:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="TestGroup">
<section name="Test" type="System.Configuration.NameValueSectionHandler"/>
</sectionGroup>
</configSections>

<TestGroup>
<Test>
<add key="Hello" value="World"/>
</Test>
</TestGroup>
</configuration>
下面是访问这个配置节组的代码:
NameValueCollection nc=(NameValueCollection)ConfigurationSettings.GetConfig("TestGroup/Test");
MessageBox.Show(nc.AllKeys[0].ToString()+" "+nc["Hello"]); //输出Hello World

--------------------编程问答-------------------- 谢谢了,不过你这个结构是简单的section结构,我的是sectiongroups结构的,所以不好弄
引用 6 楼 Return_false 的回复:
配置节点配置有问题吧

你应该配置<section>节点

配置节组是使用<sectionGroup>元素,将类似的配置节分到同一个组中。配置节组声明部分将创建配置节的包含元素,在<configSections>元素中声明配置节组,并将属于该组的节置于<sectionGroup>元素中。下面是一个包含配置节组的配置文件的例子:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="TestGroup">
<section name="Test" type="System.Configuration.NameValueSectionHandler"/>
</sectionGroup>
</configSections>

<TestGroup>
<Test>
<add key="Hello" value="World"/>
</Test>
</TestGroup>
</configuration>
下面是访问这个配置节组的代码:
NameValueCollection nc=(NameValueCollection)ConfigurationSettings.GetConfig("TestGroup/Test");
MessageBox.Show(nc.AllKeys[0].ToString()+" "+nc["Hello"]); //输出Hello World
补充:.NET技术 ,  ASP.NET
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,