欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

asp.net 读取配置文件方法

程序员文章站 2024-03-06 14:16:44
方法1: 复制代码 代码如下: system.collections.specialized.namevaluecollection nvc = (system.colle...
方法1:
复制代码 代码如下:

system.collections.specialized.namevaluecollection nvc = (system.collections.specialized.namevaluecollection)
system.configuration.configurationmanager.getsection(sectionname);

string keyvalue = nvc.getvalues(keyname)[0].tostring();
方法2:
复制代码 代码如下:
system.web.configuration.webconfigurationmanager.appsettings[keyname].tostring();

参考下面的文章

在c#中如何读取配置文件
1. 配置文件概述:
应 用程序配置文件是标准的 xml 文件,xml 标记和属性是区分大小写的。它是可以按需要更改的,开发人员可以使用配置文件来更改设置,而不必重编译应用程序。配置文件的根节点是 configuration。我们经常访问的是appsettings,它是由.net预定义配置节。我们经常使用的配置文件的架构是象下面的形式。先大 概有个印象,通过后面的实例会有一个比较清楚的认识。下面的“配置节”可以理解为进行配置一个xml的节点。
常见配置文件模式:
复制代码 代码如下:

<configuration>
<configsections> //配置节声明区域,包含配置节和命名空间声明
<section> //配置节声明
  <sectiongroup> //定义配置节组
   <section> //配置节组中的配置节声明
<appsettings> //预定义配置节
<custom element for configuration section> //配置节设置区域

2. 只有appsettings节的配置文件及访问方法
下面是一个最常见的应用程序配置文件的例子,只有appsettings节。
复制代码 代码如下:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appsettings>
<add key="connectionstring" value="user id=sa;data source=.;password=;initial catalog=test;provider=sqloledb.1;" />
<add key="templatepath" value="template" />
</appsettings>
</configuration>

下面来看看这样的配置文件如何方法。
string _connectionstring=configurationsettings.appsettings["connectionstring"];
使用configurationsettings类的静态属性appsettings就可以直接方法配置文件中的配置信息。这个属性的类型是namevaluecollection。
3. 自定义配置文件
3.1 自定义配置节
一个用户自定义的配置节,在配置文件中分为两部分:一是在<configsections></ configsections>配置节中声明配置节(上面配置文件模式中的“<section>”),另外是在< configsections></ configsections >之后设置配置节(上面配置文件模式中的“<custom element for configuration section>”),有点类似一个变量先声明,后使用一样。声明一个配置文件的语句如下:
<section name=" " type=" "/>
<section>:声明新配置节,即可创建新配置节。
name:自定义配置节的名称。
type:自定义配置节的类型,主要包括system.configuration.singletagsectionhandler、 system.configuration.dictionarysectionhandler、 system.configuration.namevaluesectionhandler。
不同的type不但设置配置节的方式不一样,最后访问配置文件的操作上也有差异。下面我们就举一个配置文件的例子,让它包含这三个不同的type。
复制代码 代码如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configsections>
<section name="test1" type="system.configuration.singletagsectionhandler"/>
<section name="test2" type="system.configuration.dictionarysectionhandler"/>
<section name="test3" type="system.configuration.namevaluesectionhandler" />
</configsections>
<test1 setting1="hello" setting2="world"/>
<test2>
<add key="hello" value="world" />
</test2>
<test3>
<add key="hello" value="world" />
</test3>
</configuration>

我们对上面的自定义配置节进行说明。在声明部分使用<section name="test1" type="system.configuration.singletagsectionhandler"/>声明了一个配置节它的名字叫 test1,类型为singletagsectionhandler。在设置配置节部分使用 <test1 setting1="hello" setting2="world"/>设置了一个配置节,它的第一个设置的值是hello,第二个值是world,当然还可以有更多。其它的两个配 置节和这个类似。
下面我们看在程序中如何访问这些自定义的配置节。我们用过configurationsettings类的静态方法getconfig来获取自定义配置节的信息。
public static object getconfig(string sectionname);
下面是访问这三个配置节的代码:
复制代码 代码如下:

//访问配置节test1
idictionary idtest1 = (idictionary)configurationsettings.getconfig("test1");
string str = (string)idtest1["setting1"] +" "+(string)idtest1["setting2"];
messagebox.show(str); //输出hello world
//访问配置节test1的方法2
string[] values1=new string[idtest1.count];
idtest1.values.copyto(values1,0);
messagebox.show(values1[0]+" "+values1[1]); //输出hello world
//访问配置节test2
idictionary idtest2 = (idictionary)configurationsettings.getconfig("test2");
string[] keys=new string[idtest2.keys.count];
string[] values=new string[idtest2.keys.count];
idtest2.keys.copyto(keys,0);
idtest2.values.copyto(values,0);
messagebox.show(keys[0]+" "+values[0]);
//访问配置节test3
namevaluecollection nc=(namevaluecollection)configurationsettings.getconfig("test3");
messagebox.show(nc.allkeys[0].tostring()+" "+nc["hello"]); //输出hello world

通过上面的代码我们可以看出,不同的type通过getconfig返回的类型不同,具体获得配置内容的方式也不一样。 配置节处理程序
返回类型
复制代码 代码如下:

singletagsectionhandler
systems.collections.idictionary
dictionarysectionhandler
systems.collections.idictionary
namevaluesectionhandler
systems.collections.specialized.namevaluecollection

3.2 自定义配置节组
配置节组是使用<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
c# 解析配置文件内容 system.configuration
1. 创建配置节类
必须创建继承自configurationsection的对象才能进行配置数据读写操作,configurationsection提供了索引器用来获取和设置配置数据,需要注意的是拥有configurationproperty特性的属性才会被存储,并且名称要保持大小写完全一致,如下面的代码中,所有的"id"必须保持一样。
复制代码 代码如下:

class configsectiondata : configurationsection
{
[configurationproperty("id")]
public int id
{
get { return (int)this["id"]; }
set { this["id"] = value; }
}
[configurationproperty("time")]
public datetime time
{
get { return (datetime)this["time"]; }
set { this["time"] = value; }
}
}

2. 创建配置文件操作对象
复制代码 代码如下:

configuration config = configurationmanager.openexeconfiguration(configurationuserlevel.none);
configsectiondata data = new configsectiondata();
data.id = 1000;
data.time = datetime.now;
config.sections.add("add", data);
config.save(configurationsavemode.minimal);

上面的例子是操作 app.config,在根节点(configuration)下写入名称为"add"的配置数据。
复制代码 代码如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configsections>
<section name="add" type="consoleapplication1.configsectiondata, ... />
</configsections>
<add id="1000" time="02/18/2006 21:51:06" />
</configuration>

需要注意的 vs2005 在ide模式下会将信息写入 *.vshost.exe.config,并且在程序关闭时覆写该文件,因此您可能看不到您写入的配置数据,只要在资源管理其中执行 *.exe 文件,您就可以在 *.exe.config 文件中看到结果了。
如果我们需要操作非缺省配置文件,可以使用execonfigurationfilemap对象。
复制代码 代码如下:

execonfigurationfilemap file = new execonfigurationfilemap();
file.execonfigfilename = "test.config";
configuration config = configurationmanager.openmappedexeconfiguration(file, configurationuserlevel.none);
configsectiondata data = new configsectiondata();
data.id = 1000;
data.time = datetime.now;
config.sections.add("add", data);
config.save(configurationsavemode.minimal);

如果我们不希望在根节点下写入配置数据,可以使用configurationsectiongroup对象。
复制代码 代码如下:

execonfigurationfilemap file = new execonfigurationfilemap();
file.execonfigfilename = "test.config";
configuration config = configurationmanager.openmappedexeconfiguration(file, configurationuserlevel.none);
configsectiondata data = new configsectiondata();
data.id = 1000;
data.time = datetime.now;
config.sectiongroups.add("group1", new configurationsectiongroup());
config.sectiongroups["group1"].sections.add("add", data);
config.save(configurationsavemode.minimal);

下面就是生成的配置文件。
复制代码 代码如下:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configsections>
<sectiongroup name="group1" type="system.configuration.configurationsectiongroup, ... >
<section name="add" type="consoleapplication1.configsectiondata, ... />
</sectiongroup>
</configsections>
<group1>
<add id="1000" time="02/18/2006 22:01:02" />
</group1>
</configuration>

3. 读取配置文件
复制代码 代码如下:

execonfigurationfilemap file = new execonfigurationfilemap();
file.execonfigfilename = "test.config";
configuration config = configurationmanager.openmappedexeconfiguration(file, configurationuserlevel.none);
configsectiondata data = config.sectiongroups["group1"].sections["add"] as configsectiondata;
//configsectiondata data = config.sections["add"] as configsectiondata; // 从根节读取
if (data != null)
{
console.writeline(data.id);
console.writeline(data.time);
}

4. 写配置文件
在写入 configurationsectiongroup 和 configurationsection 前要判断同名配置是否已经存在,否则会写入失败。
另外如果配置文件被其他configuration对象修改,则保存会失败,并抛出异常。建议采用singleton模式。
复制代码 代码如下:

execonfigurationfilemap file = new execonfigurationfilemap();
file.execonfigfilename = "test.config";
configuration config = configurationmanager.openmappedexeconfiguration(file, configurationuserlevel.none);
configsectiondata data = new configsectiondata();
data.id = 2000;
data.time = datetime.now;
configurationsectiongroup group1 = config.sectiongroups["group1"];
if (group1 == null)
config.sectiongroups.add("group1", new configurationsectiongroup());
configurationsection data = group1.sections["add"] as config;
if (add == null)
config.sectiongroups["group1"].sections.add("add", data);
else
{
group1.sections.remove("add");
group1.sections.add("add", data);
// 或者直接修改原配置对象,前提是类型转换要成功。
//configsectiondata configdata = add as configsectiondata;
//configdata.id = data.id;
//configdata.time = data.time;
}
config.save(configurationsavemode.minimal);

5. 删除配置节
复制代码 代码如下:

删除configurationsectiongroup
config.sectiongroups.remove("group1");
//config.sectiongroups.clear();
config.save(configurationsavemode.minimal);
删除configurationsection
config.sections.remove("add1");
//config.sections.clear();
if (config.sectiongroups["group1"] != null)
{
config.sectiongroups["group1"].sections.remove("add2");
//config.sectiongroups["group1"].sections.clear();
}
config.save(configurationsavemode.minimal);

6. 其他
可以使用 configurationmanager.openmachineconfiguration() 来操作 machine.config 文件。
或者使用 system.web.configuration 名字空间中的 webconfigurationmanager 类来操作 asp.net 配置文件。
configurationmanager还提供了appsettings、connectionstrings、getsection()等便捷操作。
7. 使用自定义类
可以使用自定义类,不过需要定义一个转换器。
复制代码 代码如下:

using system;
using system.collections;
using system.collections.generic;
using system.configuration;
using system.globalization;
using system.componentmodel;
// 要写入配置文件的自定义类
class customdata
{
public customdata(string s)
{
this.s = s;
}
private string s;
public string s
{
get { return s; }
set { s = value; }
}
}
// 自定义的转换器(演示代码省略了类型判断)
class customconvert : configurationconverterbase
{
public override bool canconvertfrom(itypedescriptorcontext ctx, type type)
{
return (type == typeof(string));
}
public override object convertto(itypedescriptorcontext ctx, cultureinfo ci, object value, type type)
{
return (value as customdata).s;
}
public override object convertfrom(itypedescriptorcontext ctx, cultureinfo ci, object data)
{
return new customdata((string)data);;
}
}
class configsectiondata : configurationsection
{
[configurationproperty("id")]
public int id
{
get { return (int)this["id"]; }
set { this["id"] = value; }
}
[configurationproperty("time")]
public datetime time
{
get { return (datetime)this["time"]; }
set { this["time"] = value; }
}
[configurationproperty("custom")]
[typeconverter(typeof(customconvert))] // 指定转换器
public customdata custom
{
get { return (customdata)this["custom"]; }
set { this["custom"] = value; }
}
}
public class program
{
static void main(string[] args)
{
configuration config = configurationmanager.openexeconfiguration(configurationuserlevel.none);
configsectiondata data = new configsectiondata();
data.id = 1000;
data.time = datetime.now;
data.custom = new customdata("abcdefg...");
config.sections.add("add", data);
config.save(configurationsavemode.minimal);
// 读取测试
configsectiondata configdata = (configsectiondata)config.sections["add"];
console.writeline(configdata.custom.s);
}
}

保存后的配置文件
复制代码 代码如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configsections>
<section name="add" type="..." />
</configsections>
<add id="1000" time="04/17/2006 22:06:58" custom="abcdefg..." />
</configuration>

更详细的信息可以看 msdn 中关于 system.configuration.configurationconverterbase 的说明。