读写配置文档app.config
在.net中提供了配置文档,让我们能够很方面的处理配置信息,这个配置是xml格式的。而且.net中已提供了一些访问这个文档的功能。
1、读取配置信息
下面是个配置文档的具体内容:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appsettings>
<add key="connenctionstring" value="*" />
<add key="tmppath" value="c:/temp" />
</appsettings>
</configuration>
.net提供了能够直接访问<appsettings>(注意大小写)元素的方法,在这元素中有很多的子元素,这些子元素名称都是“add”,有两个属性分别是“key”和“value”。一般情况下我们能够将自己的配置信息写在这个区域中,通过下面的方式进行访问:
string constring=system.configuration.configurationsettings.appsettings["connenctionstring"];
在appsettings后面的是子元素的key属性的值,例如appsettings["connenctionstring"],我们就是访问<add key="connenctionstring" value="*" />这个子元素,他的返回值就是“*”,即value属性的值。
2、配置配置信息
假如配置信息是静态的,我们能够手工配置,要注意格式。假如配置信息是动态的,就需要我们写程式来实现。在.net中没有写配置文档的功能,我们能够使用操作xml文档的方式来操作配置文档。下面就是个写配置文档的例子。
private void saveconfig(string connenctionstring)
{
xmldocument doc=new xmldocument();
//获得配置文档的全路径
string strfilename=appdomain.currentdomain.basedirectory.tostring()+"code.exe.config";
doc.load(strfilename);
//找出名称为“add”的任何元素
xmlnodelist nodes=doc.getelementsbytagname("add");
for(int i=0;i<nodes.count;i++)
{
//获得将当前元素的key属性
xmlattribute att=nodes[i].attributes["key"];
//根据元素的第一个属性来判断当前的元素是不是目标元素
if (att.value=="connectionstring")
{
//对目标元素中的第二个属性赋值
att=nodes[i].attributes["value"];
att.value=connenctionstring;
break;
}
}
//保存上面的修改
doc.save(strfilename);
}