读写.NET应用程序配置文件

1.读取配置文件

有如下的配置文件

 

代码
<xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ApplicationTitle" value="DevAsp Application Configuration Sample" />
<add key="ApplicationHeaderText" value="DevAsp" />
</appSettings>

<connectionStrings>
<add name="ConnectionString" connectionString="user id=DevAsp;data source=Northwind;persist security info=True;initial catalog=Comments;password=abc"

providerName
="System.Data.SqlClient" />
</connectionStrings>
</configuration>

读取ApplicationTitle,代码如下:

 

ConfigurationSettings.AppSettings["ApplicationTitle"];

读取连接字符串的代码:

ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();

 2.写入配置文件

假设有如下配置文件:

代码
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Test1" value="My value 1" />
<add key="Test2" value="Another value 2" />
</appSettings>
</configuration>
写配置文件的代码:

代码
using System;
using System.Xml;
using System.Configuration;
using System.Reflection;
//...


public class ConfigSettings
{
private ConfigSettings() {}

public static string ReadSetting(string key)
{
return ConfigurationSettings.AppSettings[key];
}

public static void WriteSetting(string key, string value)
{
// load config document for current assembly
XmlDocument doc = loadConfigDocument();

// retrieve appSettings node
XmlNode node = doc.SelectSingleNode("//appSettings");

if (node == null)
throw new InvalidOperationException("appSettings section not found in config file.");

try
{
// select the 'add' element that contains the key
XmlElement elem = (XmlElement)node.SelectSingleNode(string.Format("//add[@key='{0}']", key));

if (elem != null)
{
// add value for key
elem.SetAttribute("value", value);
}
else
{
// key was not found so create the 'add' element
// and set it's key/value attributes
elem = doc.CreateElement("add");
elem.SetAttribute(
"key", key);
elem.SetAttribute(
"value", value);
node.AppendChild(elem);
}
doc.Save(getConfigFilePath());
}
catch
{
throw;
}
}

public static void RemoveSetting(string key)
{
// load config document for current assembly
XmlDocument doc = loadConfigDocument();

// retrieve appSettings node
XmlNode node = doc.SelectSingleNode("//appSettings");

try
{
if (node == null)
throw new InvalidOperationException("appSettings section not found in config file.");
else
{
// remove 'add' element with coresponding key
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);
}
}

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);
}
}

private static string getConfigFilePath()
{
return Assembly.GetExecutingAssembly().Location + ".config";
}
}

例如:

代码
// read the Test1 value from the config file
string test1 = ConfigSettings.ReadSetting("Test1");



// write a new value for the Test1 setting
ConfigSettings.WriteSetting("Test1", "This is my new value");

// remove the Test1 setting from the config file
ConfigSettings.RemoveSetting("Test1");


如果想获取web工程的配置:
System.Web.HttpContext.Current.Server.MapPath("web.config");


posted on 2010-07-26 11:30  viva9@xian  阅读(5562)  评论(2编辑  收藏  举报

导航