您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“.net中讀寫config文件的各種方法以及config文件與XML文件的差別”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“.net中讀寫config文件的各種方法以及config文件與XML文件的差別”吧!
config文件 - 自定義配置節(jié)點
為什么要自定義的配置節(jié)點?
確實,有很多人在使用config文件都是直接使用appSetting的,把所有的配置參數(shù)全都塞到那里,這樣做雖然不錯, 但是如果參數(shù)過多,這種做法的缺點也會明顯地暴露出來:appSetting中的配置參數(shù)項只能按key名來訪問,不能支持復雜的層次節(jié)點也不支持強類型, 而且由于全都只使用這一個集合,你會發(fā)現(xiàn):完全不相干的參數(shù)也要放在一起!
想擺脫這種困擾嗎?自定義的配置節(jié)點將是解決這個問題的一種可行方法。
首先,我們來看一下如何在app.config或者web.config中增加一個自定義的配置節(jié)點。 在這篇博客中,我將介紹4種自定義配置節(jié)點的方式,最終的配置文件如下:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="MySection111" type="RwConfigDemo.MySection1, RwConfigDemo" /> <section name="MySection222" type="RwConfigDemo.MySection2, RwConfigDemo" /> <section name="MySection333" type="RwConfigDemo.MySection3, RwConfigDemo" /> <section name="MySection444" type="RwConfigDemo.MySection4, RwConfigDemo" /> </configSections> <MySection111 username="fish-li" url="https://www.jb51.net/"></MySection111> <MySection222> <users username="fish" password="liqifeng"></users> </MySection222> <MySection444> <add key="aa" value="11111"></add> <add key="bb" value="22222"></add> <add key="cc" value="33333"></add> </MySection444> <MySection333> <Command1> <![CDATA[ create procedure ChangeProductQuantity( @ProductID int, @Quantity int ) as update Products set Quantity = @Quantity where ProductID = @ProductID; ]]> </Command1> <Command2> <![CDATA[ create procedure DeleteCategory( @CategoryID int ) as delete from Categories where CategoryID = @CategoryID; ]]> </Command2> </MySection333> </configuration>
同時,我還提供所有的示例代碼(文章結(jié)尾處可供下載),演示程序的界面如下:
config文件 - Property
先來看最簡單的自定義節(jié)點,每個配置值以屬性方式存在:
<MySection111 username="fish-li" url="https://www.jb51.net/"></MySection111>
實現(xiàn)代碼如下:
public class MySection1 : ConfigurationSection { [ConfigurationProperty("username", IsRequired = true)] public string UserName { get { return this["username"].ToString(); } set { this["username"] = value; } } [ConfigurationProperty("url", IsRequired = true)] public string Url { get { return this["url"].ToString(); } set { this["url"] = value; } } }
小結(jié):
1. 自定義一個類,以ConfigurationSection為基類,各個屬性要加上[ConfigurationProperty] ,ConfigurationProperty的構(gòu)造函數(shù)中傳入的name字符串將會用于config文件中,表示各參數(shù)的屬性名稱。
2. 屬性的值的讀寫要調(diào)用this[],由基類去保存,請不要自行設(shè)計Field來保存。
3. 為了能使用配置節(jié)點能被解析,需要在<configSections>中注冊: <section name="MySection111" type="RwConfigDemo.MySection1, RwConfigDemo" /> ,且要注意name="MySection111"要與<MySection111 ..... >是對應的。
說明:下面將要介紹另三種配置節(jié)點,雖然復雜一點,但是一些基礎(chǔ)的東西與這個節(jié)點是一樣的,所以后面我就不再重復說明了。
config文件 - Element
再來看個復雜點的,每個配置項以XML元素的方式存在:
<MySection222> <users username="fish" password="liqifeng"></users> </MySection222>
實現(xiàn)代碼如下:
public class MySection2 : ConfigurationSection { [ConfigurationProperty("users", IsRequired = true)] public MySectionElement Users { get { return (MySectionElement)this["users"]; } } } public class MySectionElement : ConfigurationElement { [ConfigurationProperty("username", IsRequired = true)] public string UserName { get { return this["username"].ToString(); } set { this["username"] = value; } } [ConfigurationProperty("password", IsRequired = true)] public string Password { get { return this["password"].ToString(); } set { this["password"] = value; } } }
小結(jié):
1. 自定義一個類,以ConfigurationSection為基類,各個屬性除了要加上[ConfigurationProperty]
2. 類型也是自定義的,具體的配置屬性寫在ConfigurationElement的繼承類中。
config文件 - CDATA
有時配置參數(shù)包含較長的文本,比如:一段SQL腳本,或者一段HTML代碼,那么,就需要CDATA節(jié)點了。假設(shè)要實現(xiàn)一個配置,包含二段SQL腳本:
<MySection333> <Command1> <![CDATA[ create procedure ChangeProductQuantity( @ProductID int, @Quantity int ) as update Products set Quantity = @Quantity where ProductID = @ProductID; ]]> </Command1> <Command2> <![CDATA[ create procedure DeleteCategory( @CategoryID int ) as delete from Categories where CategoryID = @CategoryID; ]]> </Command2> </MySection333>
實現(xiàn)代碼如下:
public class MySection3 : ConfigurationSection { [ConfigurationProperty("Command1", IsRequired = true)] public MyTextElement Command1 { get { return (MyTextElement)this["Command1"]; } } [ConfigurationProperty("Command2", IsRequired = true)] public MyTextElement Command2 { get { return (MyTextElement)this["Command2"]; } } } public class MyTextElement : ConfigurationElement { protected override void DeserializeElement(System.Xml.XmlReader reader, bool serializeCollectionKey) { CommandText = reader.ReadElementContentAs(typeof(string), null) as string; } protected override bool SerializeElement(System.Xml.XmlWriter writer, bool serializeCollectionKey) { if( writer != null ) writer.WriteCData(CommandText); return true; } [ConfigurationProperty("data", IsRequired = false)] public string CommandText { get { return this["data"].ToString(); } set { this["data"] = value; } } }
小結(jié):
1. 在實現(xiàn)上大體可參考MySection2,
2. 每個ConfigurationElement由我們來控制如何讀寫XML,也就是要重載方法SerializeElement,DeserializeElement
config文件 - Collection
<MySection444> <add key="aa" value="11111"></add> <add key="bb" value="22222"></add> <add key="cc" value="33333"></add> </MySection444>
這種類似的配置方式,在ASP.NET的HttpHandler, HttpModule中太常見了,想不想知道如何實現(xiàn)它們? 代碼如下:
小結(jié):
1. 為每個集合中的參數(shù)項創(chuàng)建一個從ConfigurationElement繼承的派生類,可參考MySection1
2. 為集合創(chuàng)建一個從ConfigurationElementCollection繼承的集合類,具體在實現(xiàn)時主要就是調(diào)用基類的方法。
3. 在創(chuàng)建ConfigurationSection的繼承類時,創(chuàng)建一個表示集合的屬性就可以了,注意[ConfigurationProperty]的各參數(shù)。
config文件 - 讀與寫
前面我逐個介紹了4種自定義的配置節(jié)點的實現(xiàn)類,下面再來看一下如何讀寫它們。
讀取配置參數(shù):
MySection1 mySectioin1 = (MySection1)ConfigurationManager.GetSection("MySection111"); txtUsername1.Text = mySectioin1.UserName; txtUrl1.Text = mySectioin1.Url; MySection2 mySectioin2 = (MySection2)ConfigurationManager.GetSection("MySection222"); txtUsername2.Text = mySectioin2.Users.UserName; txtUrl2.Text = mySectioin2.Users.Password; MySection3 mySection3 = (MySection3)ConfigurationManager.GetSection("MySection333"); txtCommand1.Text = mySection3.Command1.CommandText.Trim(); txtCommand2.Text = mySection3.Command2.CommandText.Trim(); MySection4 mySection4 = (MySection4)ConfigurationManager.GetSection("MySection444"); txtKeyValues.Text = string.Join("\r\n", (from kv in mySection4.KeyValues.Cast<MyKeyValueSetting>() let s = string.Format("{0}={1}", kv.Key, kv.Value) select s).ToArray());
小結(jié):在讀取自定節(jié)點時,我們需要調(diào)用ConfigurationManager.GetSection()得到配置節(jié)點,并轉(zhuǎn)換成我們定義的配置節(jié)點類,然后就可以按照強類型的方式來訪問了。
寫配置文件:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); MySection1 mySectioin1 = config.GetSection("MySection111") as MySection1; mySectioin1.UserName = txtUsername1.Text.Trim(); mySectioin1.Url = txtUrl1.Text.Trim(); MySection2 mySection2 = config.GetSection("MySection222") as MySection2; mySection2.Users.UserName = txtUsername2.Text.Trim(); mySection2.Users.Password = txtUrl2.Text.Trim(); MySection3 mySection3 = config.GetSection("MySection333") as MySection3; mySection3.Command1.CommandText = txtCommand1.Text.Trim(); mySection3.Command2.CommandText = txtCommand2.Text.Trim(); MySection4 mySection4 = config.GetSection("MySection444") as MySection4; mySection4.KeyValues.Clear(); (from s in txtKeyValues.Lines let p = s.IndexOf('=') where p > 0 select new MyKeyValueSetting { Key = s.Substring(0, p), Value = s.Substring(p + 1) } ).ToList() .ForEach(kv => mySection4.KeyValues.Add(kv)); config.Save();
小結(jié):在修改配置節(jié)點前,我們需要調(diào)用ConfigurationManager.OpenExeConfiguration(),然后調(diào)用config.GetSection()在得到節(jié)點后,轉(zhuǎn)成我們定義的節(jié)點類型, 然后就可以按照強類型的方式來修改我們定義的各參數(shù)項,最后調(diào)用config.Save();即可。
注意:
1. .net為了優(yōu)化配置節(jié)點的讀取操作,會將數(shù)據(jù)緩存起來,如果希望使用修改后的結(jié)果生效,您還需要調(diào)用ConfigurationManager.RefreshSection(".....")
2. 如果是修改web.config,則需要使用 WebConfigurationManager
讀寫 .net framework中已經(jīng)定義的節(jié)點
前面一直在演示自定義的節(jié)點,那么如何讀取.net framework中已經(jīng)定義的節(jié)點呢?
假如我想讀取下面配置節(jié)點中的發(fā)件人。
<system.net> <mailSettings> <smtp from="Fish.Q.Li@newegg.com"> <network /> </smtp> </mailSettings> </system.net>
讀取配置參數(shù):
SmtpSection section = ConfigurationManager.GetSection("system.net/mailSettings/smtp") as SmtpSection; labMailFrom.Text = "Mail From: " + section.From;
寫配置文件:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); SmtpSection section = config.GetSection("system.net/mailSettings/smtp") as SmtpSection; section.From = "Fish.Q.Li@newegg.com2"; config.Save();
xml配置文件
前面演示在config文件中創(chuàng)建自定義配置節(jié)點的方法,那些方法也只適合在app.config或者web.config中,如果您的配置參數(shù)較多, 或者打算將一些數(shù)據(jù)以配置文件的形式單獨保存,那么,直接讀寫整個XML將會更方便。 比如:我有一個實體類,我想將它保存在XML文件中,有可能是多條記錄,也可能是一條。
這次我來反過來說,假如我們先定義了XML的結(jié)構(gòu),是下面這個樣子的,那么我將怎么做呢?
<?xml version="1.0" encoding="utf-8"?> <ArrayOfMyCommand xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <MyCommand Name="InsretCustomer" Database="MyTestDb"> <Parameters> <Parameter Name="Name" Type="DbType.String" /> <Parameter Name="Address" Type="DbType.String" /> </Parameters> <CommandText>insret into .....</CommandText> </MyCommand> </ArrayOfMyCommand>
對于上面的這段XML結(jié)構(gòu),我們可以在C#中先定義下面的類,然后通過序列化及反序列化的方式來實現(xiàn)對它的讀寫。
C#類的定義如下:
public class MyCommand { [XmlAttribute("Name")] public string CommandName; [XmlAttribute] public string Database; [XmlArrayItem("Parameter")] public List<MyCommandParameter> Parameters = new List<MyCommandParameter>(); [XmlElement] public string CommandText; } public class MyCommandParameter { [XmlAttribute("Name")] public string ParamName; [XmlAttribute("Type")] public string ParamType; }
有了這二個C#類,讀寫這段XML就非常容易了。以下就是相應的讀寫代碼:
private void btnReadXml_Click(object sender, EventArgs e) { btnWriteXml_Click(null, null); List<MyCommand> list = XmlHelper.XmlDeserializeFromFile<List<MyCommand>>(XmlFileName, Encoding.UTF8); if( list.Count > 0 ) MessageBox.Show(list[0].CommandName + ": " + list[0].CommandText, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information); } private void btnWriteXml_Click(object sender, EventArgs e) { MyCommand command = new MyCommand(); command.CommandName = "InsretCustomer"; command.Database = "MyTestDb"; command.CommandText = "insret into ....."; command.Parameters.Add(new MyCommandParameter { ParamName = "Name", ParamType = "DbType.String" }); command.Parameters.Add(new MyCommandParameter { ParamName = "Address", ParamType = "DbType.String" }); List<MyCommand> list = new List<MyCommand>(1); list.Add(command); XmlHelper.XmlSerializeToFile(list, XmlFileName, Encoding.UTF8); }
小結(jié):
1. 讀寫整個XML最方便的方法是使用序列化反序列化。
2. 如果您希望某個參數(shù)以Xml Property的形式出現(xiàn),那么需要使用[XmlAttribute]修飾它。
3. 如果您希望某個參數(shù)以Xml Element的形式出現(xiàn),那么需要使用[XmlElement]修飾它。
4. 如果您希望為某個List的項目指定ElementName,則需要[XmlArrayItem]
5. 以上3個Attribute都可以指定在XML中的映射別名。
6. 寫XML的操作是通過XmlSerializer.Serialize()來實現(xiàn)的。
7. 讀取XML文件是通過XmlSerializer.Deserialize來實現(xiàn)的。
8. List或Array項,請不要使用[XmlElement],否則它們將以內(nèi)聯(lián)的形式提升到當前類,除非你再定義一個容器類。
XmlHelper的實現(xiàn)如下:
public static class XmlHelper { private static void XmlSerializeInternal(Stream stream, object o, Encoding encoding) { if( o == null ) throw new ArgumentNullException("o"); if( encoding == null ) throw new ArgumentNullException("encoding"); XmlSerializer serializer = new XmlSerializer(o.GetType()); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.NewLineChars = "\r\n"; settings.Encoding = encoding; settings.IndentChars = " "; using( XmlWriter writer = XmlWriter.Create(stream, settings) ) { serializer.Serialize(writer, o); writer.Close(); } } /// <summary> /// 將一個對象序列化為XML字符串 /// </summary> /// <param name="o">要序列化的對象</param> /// <param name="encoding">編碼方式</param> /// <returns>序列化產(chǎn)生的XML字符串</returns> public static string XmlSerialize(object o, Encoding encoding) { using( MemoryStream stream = new MemoryStream() ) { XmlSerializeInternal(stream, o, encoding); stream.Position = 0; using( StreamReader reader = new StreamReader(stream, encoding) ) { return reader.ReadToEnd(); } } } /// <summary> /// 將一個對象按XML序列化的方式寫入到一個文件 /// </summary> /// <param name="o">要序列化的對象</param> /// <param name="path">保存文件路徑</param> /// <param name="encoding">編碼方式</param> public static void XmlSerializeToFile(object o, string path, Encoding encoding) { if( string.IsNullOrEmpty(path) ) throw new ArgumentNullException("path"); using( FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write) ) { XmlSerializeInternal(file, o, encoding); } } /// <summary> /// 從XML字符串中反序列化對象 /// </summary> /// <typeparam name="T">結(jié)果對象類型</typeparam> /// <param name="s">包含對象的XML字符串</param> /// <param name="encoding">編碼方式</param> /// <returns>反序列化得到的對象</returns> public static T XmlDeserialize<T>(string s, Encoding encoding) { if( string.IsNullOrEmpty(s) ) throw new ArgumentNullException("s"); if( encoding == null ) throw new ArgumentNullException("encoding"); XmlSerializer mySerializer = new XmlSerializer(typeof(T)); using( MemoryStream ms = new MemoryStream(encoding.GetBytes(s)) ) { using( StreamReader sr = new StreamReader(ms, encoding) ) { return (T)mySerializer.Deserialize(sr); } } } /// <summary> /// 讀入一個文件,并按XML的方式反序列化對象。 /// </summary> /// <typeparam name="T">結(jié)果對象類型</typeparam> /// <param name="path">文件路徑</param> /// <param name="encoding">編碼方式</param> /// <returns>反序列化得到的對象</returns> public static T XmlDeserializeFromFile<T>(string path, Encoding encoding) { if( string.IsNullOrEmpty(path) ) throw new ArgumentNullException("path"); if( encoding == null ) throw new ArgumentNullException("encoding"); string xml = File.ReadAllText(path, encoding); return XmlDeserialize<T>(xml, encoding); } }
xml配置文件 - CDATA
在前面的演示中,有個不完美的地方,我將SQL腳本以普通字符串的形式輸出到XML中了:
<CommandText>insret into .....</CommandText>
顯然,現(xiàn)實中的SQL腳本都是比較長的,而且還可能會包含一些特殊的字符,這種做法是不可取的,好的處理方式應該是將它以CDATA的形式保存, 為了實現(xiàn)這個目標,我們就不能直接按照普通字符串的方式來處理了,這里我定義了一個類 MyCDATA:
public class MyCDATA : IXmlSerializable { private string _value; public MyCDATA() { } public MyCDATA(string value) { this._value = value; } public string Value { get { return _value; } } XmlSchema IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader reader) { this._value = reader.ReadElementContentAsString(); } void IXmlSerializable.WriteXml(XmlWriter writer) { writer.WriteCData(this._value); } public override string ToString() { return this._value; } public static implicit operator MyCDATA(string text) { return new MyCDATA(text); } }
我將使用這個類來控制CommandText在XML序列化及反序列化的行為,讓它寫成一個CDATA形式, 因此,我還需要修改CommandText的定義,改成這個樣子:
public MyCDATA CommandText;
最終,得到的結(jié)果是:
<?xml version="1.0" encoding="utf-8"?> <ArrayOfMyCommand xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <MyCommand Name="InsretCustomer" Database="MyTestDb"> <Parameters> <Parameter Name="Name" Type="DbType.String" /> <Parameter Name="Address" Type="DbType.String" /> </Parameters> <CommandText><![CDATA[insret into .....]]></CommandText> </MyCommand> </ArrayOfMyCommand>
xml文件讀寫注意事項
通常,我們使用使用XmlSerializer.Serialize()得到的XML字符串的開頭處,包含一段XML聲明元素:
<?xml version="1.0" encoding="utf-8"?>
由于各種原因,有時候可能不需要它。為了讓這行字符消失,我見過有使用正則表達式去刪除它的,也有直接分析字符串去刪除它的。 這些方法,要么浪費程序性能,要么就要多寫些奇怪的代碼??傊褪强雌饋砗軇e扭。 其實,我們可以反過來想一下:能不能在序列化時,不輸出它呢? 不輸出它,不就達到我們期望的目的了嗎?
在XML序列化時,有個XmlWriterSettings是用于控制寫XML的一些行為的,它有一個OmitXmlDeclaration屬性,就是專門用來控制要不要輸出那行XML聲明的。 而且,這個XmlWriterSettings還有其它的一些常用屬性。請看以下演示代碼:
using( MemoryStream stream = new MemoryStream() ) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.NewLineChars = "\r\n"; settings.OmitXmlDeclaration = true; settings.IndentChars = "\t"; XmlWriter writer = XmlWriter.Create(stream, settings);
使用上面這段代碼,我可以:
1. 不輸出XML聲明。
2. 指定換行符。
3. 指定縮進字符。
如果不使用這個類,恐怕還真的不能控制XmlSerializer.Serialize()的行為。
前面介紹了讀寫XML的方法,可是,如何開始呢? 由于沒有XML文件,程序也沒法讀取,那么如何得到一個格式正確的XML呢? 答案是:先寫代碼,創(chuàng)建一個要讀取的對象,隨便輸入一些垃圾數(shù)據(jù),然后將它寫入XML(反序列化), 然后,我們可以參考生成的XML文件的具體格式,或者新增其它的節(jié)點(列表), 或者修改前面所說的垃圾數(shù)據(jù),最終得到可以使用的,有著正確格式的XML文件。
配置參數(shù)的建議保存方式
經(jīng)常見到有很多組件或者框架,都喜歡把配置參數(shù)放在config文件中, 那些設(shè)計者或許認為他們的作品的參數(shù)較復雜,還喜歡搞自定義的配置節(jié)點。 結(jié)果就是:config文件中一大堆的配置參數(shù)。最麻煩的是:下次其它項目還要使用這個東西時,還得繼續(xù)配置!
.net一直提倡XCOPY,但我發(fā)現(xiàn)遵守這個約定的組件或者框架還真不多。 所以,我想建議大家在設(shè)計組件或者框架的時候:
1. 請不要把你們的參數(shù)放在config文件中,那種配置真的不方便【復用】。
2. 能不能同時提供配置文件以及API接口的方式公開參數(shù),由用戶來決定如何選擇配置參數(shù)的保存方式。
config文件與XML文件的差別
從本質(zhì)上說,config文件也是XML文件,但它們有一點差別,不僅僅是因為.net framework為config文件預定義了許多配置節(jié)。 對于ASP.NET應用程序來說,如果我們將參數(shù)放在web.config中,那么,只要修改了web.config,網(wǎng)站也將會重新啟動, 此時有一個好處:我們的代碼總是能以最新的參數(shù)運行。另一方面,也有一個壞處:或許由于種種原因,我們并不希望網(wǎng)站被重啟, 畢竟重啟網(wǎng)站會花費一些時間,這會影響網(wǎng)站的響應。 對于這個特性,我只能說,沒有辦法,web.config就是這樣。
然而,當我們使用XML時,顯然不能直接得到以上所說的特性。因為XML文件是由我們自己來維護的。
到此,相信大家對“.net中讀寫config文件的各種方法以及config文件與XML文件的差別”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學習!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。