大家都開發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
