配置文件是标准的XML文件,.NET Framework在配置文件里定义了自己的一组元素以便开发者方便的实现程序配置。
如何使用config文件在.Net application:
第一:引用 System.Configuration在.net tab下
第二:using using System.Configuration;
第三:修改你自己的配置文件,例如保存用户信息:
第四:使用配置文件。例如读取indexpath值
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="serverName" value=""/>
<add key="userName" value=""/>
<add key="password" value=""/>
<add key="indexpath" value="C:\index"/>
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
indexPath = ConfigurationManager.AppSettings["indexpath"];
配置文件中元素的用法:
参考官方文档:http://msdn.microsoft.com/en-us/library/1fk1t1t0(v=vs.100).aspx
在library中使用config文件:
在library中增加config文件后,似乎不能用微软的配置文件管理API来操作(至少我没有找到), 需要自己用XML操作方式来使用。
/// <summary>
/// Get property of config file
/// </summary>
/// <param name="file">config file</param>
/// <param name="key"></param>
/// <returns></returns>
private static string GetAttributeValue(string file, string key)
{
string value = string.Empty;
try
{
if (File.Exists(file))
{
XmlDocument xml = new XmlDocument();
xml.Load(file);
XmlNode xNode = xml.SelectSingleNode("//appSettings");
XmlElement element = (XmlElement)xNode.SelectSingleNode("//add[@key='" + key + "']");
value = element.GetAttribute("value").ToString();
}
}
catch(Exception e)
{
throw new Exception("Read log4config file fail!", e);
}
return value;
}
有多个配置文件的情况:
例如下图:
对于类库,新建的配置文件默认不会被copy到主程序编译目录下,需要修改为Copy always:
如有有理解不到地方希望大家指正,谢谢
Useful link:
http://www.oschina.net/translate/why-where-and-how-of-net-configuration-files