大家都开发winform程序时候会大量用到配置App.config作为保持用户设置的基本信息,比如记住用户名,这样的弊端就是每个人一些个性化的设置每次更新程序的时候会被覆盖。
故将配置文件分两大类:
公用系统配置文件(App.config)和私用配置文件(xml文件).
一、公用系统配置文件(App.config)的读写操作。本文参考:http://www.cnblogs.com/dotnet_way/archive/2010/07/26/config_file.html#2902913
1.读取配置文件 有如下的配置文件 代码 读取ApplicationTitle,代码如下: ConfigurationSettings.AppSettings[ "ApplicationTitle" ]; 读取连接字符串的代码: ConfigurationManager.ConnectionStrings[ "ConnectionString" ].ToString(); 2.写入配置文件 假设有如下配置文件: 代码 复制代码 复制代码 写配置文件的代码: 复制代码 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" ; } } 复制代码 例如: 代码复制代码 复制代码 如果想获取web工程的配置: System.Web.HttpContext.Current.Server.MapPath( "web.config" ); |
二、私用配置文件(xml文件).
using
System; using
System.Collections.Generic; using
System.Linq; using
System.Text; using
System.Windows.Forms; using
System.IO; using
System.Xml.Serialization; 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 { XmlSerializer serializer = new
XmlSerializer( typeof (List<UserProfie>)); using
(FileStream stream = new
FileStream(filePath, FileMode.Create)) { serializer.Serialize(stream, userProfies); } } 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); } } 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 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> |
WinForm程序如何更好的选择配置文件,布布扣,bubuko.com
原文:http://www.cnblogs.com/zfanlong1314/p/3623622.html