大家都开发winform程序时候会大量用到配置App.config作为保持用户设置的基本信息,比如记住用户名,这样的弊端就是每个人一些个性化的设置每次更新程序的时候会被覆盖。
故将配置文件分两大类:
公用系统配置文件(App.config)和私用配置文件(xml文件).
一、公用系统配置文件(App.config)的读写操作。本文参考:http://www.cnblogs.com/dotnet_way/archive/2010/07/26/config_file.html#2902913
读写.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)
{
//不建议通过这种自带的方式进行读取;如果手动修改了配置文件,则不会第二次读取的时候,依旧是内存中的值。可以通过XML方式进行读取。 //return ConfigurationSettings.AppSettings[key];
// 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
return elem.GetAttribute("value");
}
}
catch
{
throw;
}
return ""
}
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");
二、私用配置文件(xml文件).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml.Serialization;
using System.Xml.Linq;
using System.Data.Linq;
namespace EmailSystem.Utility.UserConfigSettings
{
[Serializable]
public class UserProfie
{
/// <summary>
///
/// </summary>
public string Key { get; set; }
/// <summary>
///
/// </summary>
public string Value { get; set; }
}
/// <summary>
///
/// </summary>
public class UserConfigXML
{
public static readonly UserConfigXML Instance = new UserConfigXML();
private string filePath;
private List<UserProfie> userProfies = new List<UserProfie>();
private UserConfigXML()
{
filePath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "UserConfig.xml");
LoadUserConfigXML();
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public string ReadSetting(string key)
{
var up = userProfies.FirstOrDefault(m => m.Key == key);
if (up != null)
return userProfies.FirstOrDefault(m => m.Key == key).Value;
else
return string.Empty;
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void WriteSetting(string key, string value)
{
var us = userProfies.FirstOrDefault(m => m.Key == key);
if (us != null)
userProfies.Remove(us);
userProfies.Add(new UserProfie { Key = key, Value = value });
SaveUserConfigXML();
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
public void RemoveSetting(string key)
{
var us = userProfies.FirstOrDefault(m => m.Key == key);
if (us != null)
{
userProfies.Remove(us);
SaveUserConfigXML();
}
}
/// <summary>
///
/// </summary>
private void SaveUserConfigXML()
{
try
{
#region [XML序列化方式]
//<?xml version="1.0"?>
//<ArrayOfUserProfie xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
// <UserProfie>
// <Key>key1</Key>
// <Value>1</Value>
// </UserProfie>
// <UserProfie>
// <Key>key2</Key>
// <Value>2</Value>
// </UserProfie>
//</ArrayOfUserProfie>
//XmlSerializer serializer = new XmlSerializer(typeof(List<UserProfie>));
//using (FileStream stream = new FileStream(filePath, FileMode.Create))
//{
// serializer.Serialize(stream, userProfies);
//}
#endregion
#region [Linq to XML方式]
//<AppSettings>
// <add key="key1" value="1" />
// <add key="key1" value="1" />
//</AppSettings>
var domLinq = new XElement("AppSettings",
from c in userProfies
select new XElement("add",
new XAttribute("key", c.Key),
new XAttribute("value", c.Value))
);
domLinq.Save(filePath);
#endregion
}
catch (Exception ex)
{
}
}
/// <summary>
///
/// </summary>
private void LoadUserConfigXML()
{
if (File.Exists(filePath))
{
try
{
XmlSerializer xs = new XmlSerializer(typeof(List<UserProfie>));
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
userProfies = (List<UserProfie>)xs.Deserialize(fs);
}
#region [Linq to XML方式]
//XDocument xdoc = XDocument.Load(filePath);
//var userConfiLst = from a in xdoc.Descendants("AppSettings").Elements("add")
// select new UserConfig
// {
// Key = a.Attribute("key").Value,
// Value = a.Attribute("value").Value,
// };
//this.userProfies = userConfiLst.ToList();
#endregion
}
catch (Exception ex)
{
}
}
}
}
public class TestClass
{
public void TestUserConfig()
{
UserConfigXML.Instance.WriteSetting("key1", "1");
UserConfigXML.Instance.WriteSetting("key2", "2");
var key = UserConfigXML.Instance.ReadSetting("key1");
UserConfigXML.Instance.ReadSetting("key2");
UserConfigXML.Instance.RemoveSetting("key2");
}
}
}
XML序列化格式:
<?xml version="1.0"?>
<ArrayOfUserProfie xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<UserProfie>
<Key>key1</Key>
<Value>1</Value>
</UserProfie>
<UserProfie>
<Key>key2</Key>
<Value>2</Value>
</UserProfie>
</ArrayOfUserProfie>
Linq to xml 格式:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<AppSettings>
<add key="key1" value="1" />
<add key="key1" value="1" />
</AppSettings>
三、改进写法:采用微软自带写法,读取本地其他config文件。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.IO;
namespace EmailSystem.Utility.UserConfigManage
{
public class UserLocalConfigSettings
{
/// <summary>
///
/// </summary>
public static readonly UserLocalConfigSettings Instance = new UserLocalConfigSettings();
/// <summary>
///
/// </summary>
private string filePath = string.Empty;
/// <summary>
///
/// </summary>
private UserLocalConfigSettings()
{
filePath = GetConfigFilePath();
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public string ReadSetting(string key)
{
ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
configFile.ExeConfigFilename = filePath;
Configuration appConf = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None);
if (appConf.AppSettings.Settings[key] != null)
return appConf.AppSettings.Settings[key].Value;
else
return string.Empty;
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void WriteSetting(string key, string value)
{
ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
configFile.ExeConfigFilename = filePath;
Configuration appConf = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None);
if (appConf.AppSettings.Settings[key] != null)
appConf.AppSettings.Settings.Remove(key);
appConf.AppSettings.Settings.Add(key, value);
appConf.Save(ConfigurationSaveMode.Modified);
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
public void RemoveSetting(string key)
{
ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
configFile.ExeConfigFilename = filePath;
Configuration appConf = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None);
if (appConf.AppSettings.Settings[key] != null)
{
appConf.AppSettings.Settings.Remove(key);
appConf.Save(ConfigurationSaveMode.Modified);
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private string GetConfigFilePath()
{
return Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "UserConfigSettings.config");
}
}
public class TestUserLocalConfigSettings
{
public void TestUserLocalConfigSettingsMethod()
{
string str1 = UserLocalConfigSettings.Instance.ReadSetting("FailedEmailTryCount");
// write a new value for the Test1 setting
UserLocalConfigSettings.Instance.WriteSetting("Test1", "This is my new value");
// remove the Test1 setting from the config file
UserLocalConfigSettings.Instance.RemoveSetting("Test1");
UserLocalConfigSettings.Instance.WriteSetting("EmailPath", "This is my new value");
}
}
}
补充:打开任意的配置文件
一、读取默认的App.config文件
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
如果采用根据指定路径名称读取的话,会调用时候会出现目录下产生一个副本文件
ConfigurationManager.OpenExeConfiguration("E:\App.config");
这个方法会在这个目录下产生一个副本文件(E:\App.config.config),
二、读取自定义本地文件的Config文件
ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
读语句:
String str = ConfigurationManager.AppSettings["DemoKey"].Value;
写语句:
Configuration config = ConfigurationManager.OpenExeConfiguration("E:\db.config");
config.AppSettings.Settings["DemoKey"].Value = "DemoValue";
config.Save();
配置文件内容格式:(db.config)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="DemoKey" value="*" />
</appSettings>
</configuration>
以上是网上转载,我仔细测试了一下,发现这段代码会有一个小问题(其实网上的人也说到了),
ConfigurationManager.OpenExeConfiguration("E:\db.config");
这个方法会在这个目录下产生一个副本文件(E:\db.config.config), 而代码真正操作的文件却不是db.config,而是程序自动创建的db.config.config文件,所以很苦恼,若删除原文件,则又会提示报错,
在这里我做了一点稍微的改动就可以达要我们想要的目的,(不生成文件副本,直接操作此文件,且更新操作也是操作此文件):
//先实例化一个ExeConfigurationFileMap对象,把物理地址赋值到它的 ExeConfigFilename 属性中;
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = @"E:\MySrc\db.config";
//再调用fileMap 实例化 config , 这样,操作的文件就是db.config文件了,也不会产生副本文件
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
//读写操作跟原来一样,不变
String str = ConfigurationManager.AppSettings["DemoKey"];
config.AppSettings.Settings["DemoKey"].Value = "DemoValue";
//写完之后一定要保存,否则不会保存到文件中去的
config.Save();
本文章转载:http://www.cppblog.com/lzyuan1006/archive/2009/12/24/103998.aspx
http://blog.csdn.net/dbzhang800/article/details/7212420
http://www.cnblogs.com/goldpicker/archive/2006/08/25/486675.html