例如:
<?xml version="1.0"?>
<configuration>
<databases>
<database name="testDB" connectionString="testConn" />
</databases>
</configuration>
<?xml version="1.0"?>
<configuration>
<databases>
<database name="testDB" connectionString="testConn" />
</databases>
</configuration>
<configuration>
<appSettings>
<add key="assembly" value="DataAccessApplicationBlock"></add>
</appSettings>
</configuration>
这样可以直接用ConfigurationSettings.AppSettings["testDB"];来读取
<add key="cConn" value="server=.;database=aaa;uid=sa;pwd=" />
</appSettings>
用System.Configuration.ConfigurationSettings.AppSettings["cConn"]读取
<appSettings>
<add key="Name" value="testDB" />
<add key="connectionString" value="testConn" />
<add key="Other" value="Otherstring" />
</appSettings>在程序中用
s1 = System.Configuration.ConfigurationSettings.AppSettings["Name"]
s2 = System.Configuration.ConfigurationSettings.AppSettings["connectionString"]
s3 = System.Configuration.ConfigurationSettings.AppSettings["Other"]
就可以读出刚才设置的字符串了
string connString = string.Empty;
try {
AppSettingsReader configurationAppSettings = new AppSettingsReader();
connString = ((string)(configurationAppSettings.GetValue("sqlConnection1.ConnectionString", typeof(string)))); } catch(Exception) {
connString = null;
} if(connString == null || connString == string.Empty) {
string path = System.Reflection.Assembly.GetExecutingAssembly().Location; path = path.Substring(0, path.LastIndexOf("\\")) + "\\BPAdminTool.exe.config"; XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlNode root = doc.DocumentElement;
XmlNode typeNode = root.SelectSingleNode("/configuration/appSettings/add[@key='sqlConnection1.ConnectionString']"); connString = typeNode.Attributes["value"].InnerText;
} return connString;
}
using System;
using System.Xml;
using System.Collections;
using System.Collections.Specialized;
using System.Configuration;
using System.Reflection;
namespace Adpost.Comm.ConfigModel
{
/// <summary>
/// Web.config 操作类
/// Copyright (C) 2006-2008 adpost
/// 定义为不可继承性
/// </summary>
public sealed class ConfigClass
{
public static string GetConfigString(string SectionName,string key)
{
if(SectionName==null || SectionName == "")
{
//try
//{
NameValueCollection cfgName = (NameValueCollection)ConfigurationSettings.GetConfig("appSettings");
if(cfgName[key] == null || cfgName[key] == "")
{
throw (new Exception("在Web.config文件中未发现配置项: \"" + key.ToString() + "\""));
}
else
{
return cfgName[key];
}
/*}
catch(NullReferenceException)
{
throw (new Exception("在Web.config文件中未发现配置项: \"" + key.ToString() + "\""));
}*/
}
else{
//try
//{
NameValueCollection cfgName = (NameValueCollection)ConfigurationSettings.GetConfig(SectionName);
if(cfgName[key] == null || cfgName[key] == "")
{
throw (new Exception("在Web.config文件中未发现配置项: \"" + key.ToString() + "\""));
}
else
{
return cfgName[key];
}
/*}
catch(NullReferenceException)
{
throw (new Exception("在Web.config文件中未发现配置项: \"" + key.ToString() + "\""));
}*/
}
/*
直接返回的方法
*/
}
/// <summary>
/// 得到配置文件中的配置decimal信息
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static decimal GetConfigDecimal(string SectionName,string key)
{
decimal result = 0;
string cfgVal = GetConfigString(SectionName,key);
if(null != cfgVal && string.Empty != cfgVal)
{
//try
//{
result = decimal.Parse(cfgVal);
/*}
catch(FormatException)
{
// Ignore format exceptions.
}*/
} return result;
}
/// <summary>
/// 得到配置文件中的配置int信息
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static int GetConfigInt(string SectionName,string key)
{
int result = 0;
string cfgVal = GetConfigString(SectionName,key);
if(null != cfgVal && string.Empty != cfgVal)
{
//try
//{
result = Int32.Parse(cfgVal);
/*}
catch(FormatException)
{
// Ignore format exceptions.
}*/
} return result;
}
/// <summary>
/// 写入配置文件
/// </summary>
/// <param name="SectionName">节点名称</param>
/// <parma name="key">键名</param>
/// <parma name="value">键值</param>
public static void SetConfigKeyValue(string SectionName,string key,string value)
{
//导入配置文件
XmlDocument doc = loadConfigDocument();
//重新取得 节点名
XmlNode node= doc.SelectSingleNode("//" + SectionName);
if (node == null)
throw new InvalidOperationException(SectionName + " section not found in config file."); try
{
// 用 'add'元件 格式化是否包含键名
// select the 'add' element that contains the key
XmlElement elem = (XmlElement)node.SelectSingleNode(string.Format("//add[@key='{0}']", key)); if (elem != null)
{
//修改或添加键值
elem.SetAttribute("value", value);
}
else
{
//如果没有发现键名则进行添加设置键名和键值
elem = doc.CreateElement("add");
elem.SetAttribute("key", key);
elem.SetAttribute("value", value);
node.AppendChild(elem);
}
doc.Save(getConfigFilePath());
}
catch
{
throw;
} }
public static void RemoveSectionKey(string SectionName,string key)
{
//导入配置文件
XmlDocument doc = loadConfigDocument(); //重新取得 节点名
XmlNode node= doc.SelectSingleNode("//" + SectionName); try
{
if (node == null)
throw new InvalidOperationException(SectionName + " section not found in config file.");
else
{
// 用 'add' 方法格式 key和value
node.RemoveChild(node.SelectSingleNode(string.Format("//add[@key='{0}']", key)));
doc.Save(getConfigFilePath());
}
}
catch (NullReferenceException e)
{
throw new Exception(string.Format("The key {0} does not exist.", key), e);
}
} /// <summary>
/// 读入配置文件
/// </summary>
private static XmlDocument loadConfigDocument()
{
XmlDocument doc = null;
try
{
doc = new XmlDocument();
doc.Load(getConfigFilePath());
return doc;
}
catch (System.IO.FileNotFoundException e)
{
throw new Exception("No configuration file found.", e);
}
}
/// <summary>
/// 取得置文件路径和名称
/// </summary>
private static string getConfigFilePath()
{
return AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
//return Assembly.GetExecutingAssembly().Location + ".config";
}
}
}
如果采用自定义节点就把 appSettings改成成你自定义的节点
NameValueCollection arrName = (NameValueCollection)ConfigurationSettings.GetConfig("appSettings");
if(arrName[name] == null || arrName[name] == "")
{
return extText;
}
else{
return arrName[name];
}
name 是你的 key
完整的过程
//取得配置文件数据内容
public static string get_Setting(string name,string extText)
{
/*
* 如果直接用appSettings可以用 ConfigurationSettings.AppSettings["ConnStr"].ToString()直接读取,自定义 section可以把下面的 appSettings改成你自定义的section name
*/
NameValueCollection arrName = (NameValueCollection)ConfigurationSettings.GetConfig("appSettings");
if(arrName[name] == null || arrName[name] == "")
{
return extText;
}
else{
return arrName[name];
}
}
name 属性,它是元素的名称,该元素包含节处理程序读取的信息。
type 属性,它是类的名称,该类读取信息。
配置设置的语法取决于与配置节关联的节处理程序。有关更多信息,请参见配置节架构。
下面的示例说明如何声明自定义节,该节使用 SingleTagSectionHandler 类。
<configuration>
<configSections>
<section name="sampleSection"
type="System.Configuration.SingleTagSectionHandler" />
</configSections> <sampleSection setting1="Value1" setting2="value two"
setting3="third value" />
</configuration>
访问自定义配置节
可以使用静态方法 System.Configuration.ConfigurationSettings.GetConfig 来从应用程序访问配置设置。实现 System.Configuration.IConfigurationSectionHandler 的类计算 GetConfig 方法返回的设置。由于 IConfigurationSectionHandler.Create 方法的返回值是 Object 类型,所以必须将对象强制转换为节处理程序创建的类型。
若要从 sampleSection 读取设置,请将 ConfigurationSettings.GetConfig 返回的对象强制转换为 IDictionary 对象。
下面的代码说明如何从配置文件中检索设置。[C#]
using System;
using System.Collections;
using System.Configuration;class MyConfigurationReader {
public void ReadMySettings() {
IDictionary sampleTable = (IDictionary)
ConfigurationSettings.GetConfig("sampleSection");
string value1 = (string)sampleTable["setting1"];
string value2 = (string)sampleTable["setting2"];
string value3 = (string)sampleTable["setting3"];
}
}