以下设置为vs2008或以上
1. 向项目添加app.config文件:
右击项目名称,选择“添加”→“添加新建项”,在出现的“添加新项”对话框中,选择“添加应用程序配置文件”;如果项目以前没有配置文件,则默认的文件名称为“app.config”,单击“确定”。出现在设计器视图中的app.config文件为:
<?xmlversion="1.0"encoding="utf-8" ?>
<configuration>
</configuration>
注意:非web程序默认为app.config,web项目默认为web.config.
2.配置文件内容格式:(app.config)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
</appSettings>
</configuration>
3.读取配置(配置文件为app.config或者web.config看项目而定):
using System.Configuration;
string filepath = ConfigurationManager.AppSettings["path"]
表示从.config中定义的类似这样的<add key="path" value="c:\\system32"/>读取值,c:\\system32
4.写入配置
Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
cfa.AppSettings.Settings["path"].Value = "c:\\system32";
cfa.Save();
ConfigurationManager.RefreshSection("appSettings"); //立即更新,因为有缓存
5.添加名字空间
想调用ConfigurationManager必须要先在工程里添加system.configuration.dll程序集的引用。
在解决方案管理器中右键点击工程名称,在右键菜单中选择添加引用,.net TablePage下即可找到
6.修改配置文件注意事项
对于web程序,修改了web.config会导致整个webapplication的重启,session和cookie也会无效,需要严重注意!
所以如需经常修改就不要保存在根目录下的web.config下了。
7.访问自定义节点
自定义的节点要通过ConfigurationManager.GetSection()来读取,得先在配置文件中设置自定义节点的信息,如下:这段代码需要放在appSettings之前,否则会出错。然后就可以添加自定义的节点了.
a.在代码中读取这些节点
using System.Collections.Specialized;
NameValueCollection config = (NameValueCollection)ConfigurationManager.GetSection("TestGroup/Test");
使用config["test1"]就能获得value值.NameValueCollection是在System.Collections.Specialized命名空间下的.这些节点的配置在Web.Config中也是一样的
b.在代码中更新这些节点(config["test1"]="值一"会报read only错误)
NameValueCollection setting = new NameValueCollection();
string strkey = PrintSetting_Str.Enable.ToString();
string strvalue = needsaving.benable.ToString();
setting.Set(strkey, strvalue);
//保存
strkey = PrintSetting_Str.Printlabel.ToString();
XmlDocument xmldoc = new XmlDocument();
XmlElement rootElement = xmldoc.createElement_x(strkey);
const string perfix = "add";
const string keyatt = "key";
const string valueatt = "value";
foreach (string item in setting.AllKeys)
{
}
xmldoc.A(rootElement);
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.Sections[strkey].SectionInformation.SetRawXml(xmldoc.OuterXml);
config.Save();