




版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領
文檔簡介
1、 讀取配置文件方法 讀取配置文件方法,需要的朋友可以參考下。方法1: 復制代碼 代碼如下:System.Collections.Specialized.NameValueCollection nvc = (System.Collections.Specialized.NameValueCollection) System.Configuration.ConfigurationManager.GetSection(sectionName); string keyValue = nvc.GetValues(keyName)0.ToString(); 方法2: 復制代碼 代碼如下:System.We
2、b.Configuration.WebConfigurationManager.AppSettingskeyName.ToString(); 參考下面的文章在C#中如何讀取配置文件 1. 配置文件概述: 應 用程序配置文件是標準的 XML 文件,XML 標記和屬性是區(qū)分大小寫的。它是可以按需要更改的,開發(fā)人員可以使用配置文件來更改設置,而不必重編譯應用程序。配置文件的根節(jié)點是 configuration。我們經(jīng)常訪問的是appSettings,它是由.Net預定義配置節(jié)。我們經(jīng)常使用的配置文件的架構是象下面的形式。先大 概有個印象,通過后面的實例會有一個比較清楚的認識。下面的“配置節(jié)”可以理解
3、為進行配置一個XML的節(jié)點。 常見配置文件模式: 復制代碼 代碼如下:<configuration> <configSections> /配置節(jié)聲明區(qū)域,包含配置節(jié)和命名空間聲明 <section> /配置節(jié)聲明 <sectionGroup> /定義配置節(jié)組 <section> /配置節(jié)組中的配置節(jié)聲明 <appSettings> /預定義配置節(jié) <Custom element for configuration section> /配置節(jié)設置區(qū)域 2. 只有appSettings節(jié)的配置文件及訪問方法 下面是
4、一個最常見的應用程序配置文件的例子,只有appSettings節(jié)。 復制代碼 代碼如下:<?xml version="1.0" encoding="utf-8"?> <configuration> <appSettings> <add key="connectionstring" value="User ID=sa;Data Source=.;Password=;Initial Catalog=test;Provider=SQLOLEDB.1;" /> <add
5、 key="TemplatePATH" value="Template" /> </appSettings> </configuration> 下面來看看這樣的配置文件如何方法。 string _connectionString=ConfigurationSettings.AppSettings"connectionstring" 使用ConfigurationSettings類的靜態(tài)屬性AppSettings就可以直接方法配置文件中的配置信息。這個屬性的類型是NameValueCollection。 3
6、. 自定義配置文件 3.1自定義配置節(jié) 一個用戶自定義的配置節(jié),在配置文件中分為兩部分:一是在<configSections></ configSections>配置節(jié)中聲明配置節(jié)(上面配置文件模式中的“<section>”),另外是在< configSections></ configSections >之后設置配置節(jié)(上面配置文件模式中的“<Custom element for configuration section>”),有點類似一個變量先聲明,后使用一樣。聲明一個配置文件的語句如下: <section n
7、ame=" " type=" "/> <section>:聲明新配置節(jié),即可創(chuàng)建新配置節(jié)。 name:自定義配置節(jié)的名稱。 type:自定義配置節(jié)的類型,主要包括System.Configuration.SingleTagSectionHandler、 System.Configuration.DictionarySectionHandler、 System.Configuration.NameValueSectionHandler。 不同的type不但設置配置節(jié)的方式不一樣,最后訪問配置文件的操作上也有差異。下面我們就舉一個配置文件的
8、例子,讓它包含這三個不同的type。 復制代碼 代碼如下:<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="Test1" type="System.Configuration.SingleTagSectionHandler"/> <section name="Test2" type="System.Confi
9、guration.DictionarySectionHandler"/> <section name="Test3" type="System.Configuration.NameValueSectionHandler" /> </configSections> <Test1 setting1="Hello" setting2="World"/> <Test2> <add key="Hello" value="Wor
10、ld" /> </Test2> <Test3> <add key="Hello" value="World" /> </Test3> </configuration> 我們對上面的自定義配置節(jié)進行說明。在聲明部分使用<section name="Test1" type="System.Configuration.SingleTagSectionHandler"/>聲明了一個配置節(jié)它的名字叫 Test1,類型為SingleTagS
11、ectionHandler。在設置配置節(jié)部分使用 <Test1 setting1="Hello" setting2="World"/>設置了一個配置節(jié),它的第一個設置的值是Hello,第二個值是World,當然還可以有更多。其它的兩個配 置節(jié)和這個類似。 下面我們看在程序中如何訪問這些自定義的配置節(jié)。我們用過ConfigurationSettings類的靜態(tài)方法GetConfig來獲取自定義配置節(jié)的信息。 public static object GetConfig(string sectionName); 下面是訪問這三個配置節(jié)的代碼: 復
12、制代碼 代碼如下:/訪問配置節(jié)Test1 IDictionary IDTest1 = (IDictionary)ConfigurationSettings.GetConfig("Test1"); string str = (string)IDTest1"setting1" +" "+(string)IDTest1"setting2" MessageBox.Show(str); /輸出Hello World /訪問配置節(jié)Test1的方法2 string values1=new stringIDTest1.Count;
13、 IDTest1.Values.CopyTo(values1,0); MessageBox.Show(values10+" "+values11); /輸出Hello World /訪問配置節(jié)Test2 IDictionary IDTest2 = (IDictionary)ConfigurationSettings.GetConfig("Test2"); string keys=new stringIDTest2.Keys.Count; string values=new stringIDTest2.Keys.Count; IDTest2.Keys.Co
14、pyTo(keys,0); IDTest2.Values.CopyTo(values,0); MessageBox.Show(keys0+" "+values0); /訪問配置節(jié)Test3 NameValueCollection nc=(NameValueCollection)ConfigurationSettings.GetConfig("Test3"); MessageBox.Show(nc.AllKeys0.ToString()+" "+nc"Hello"); /輸出Hello World 通過上面的代碼我們
15、可以看出,不同的type通過GetConfig返回的類型不同,具體獲得配置內(nèi)容的方式也不一樣。 配置節(jié)處理程序 返回類型 復制代碼 代碼如下:SingleTagSectionHandler Systems.Collections.IDictionary DictionarySectionHandler Systems.Collections.IDictionary NameValueSectionHandler Systems.Collections.Specialized.NameValueCollection 3.2自定義配置節(jié)組 配置節(jié)組是使用<sectionGroup>元素
16、,將類似的配置節(jié)分到同一個組中。配置節(jié)組聲明 部分將創(chuàng)建配置節(jié)的包含元素,在<configSections>元素中聲明配置節(jié)組,并將屬于該組的節(jié)置于< sectionGroup>元素中。下面是一個包含配置節(jié)組的配置文件的例子: 復制代碼 代碼如下:<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <sectionGroup name="TestGroup"> <s
17、ection name="Test" type="System.Configuration.NameValueSectionHandler"/> </sectionGroup> </configSections> <TestGroup> <Test> <add key="Hello" value="World"/> </Test> </TestGroup> </configuration> 下面是訪問這個配置節(jié)組的
18、代碼: NameValueCollection nc=(NameValueCollection)ConfigurationSettings.GetConfig("TestGroup/Test"); MessageBox.Show(nc.AllKeys0.ToString()+" "+nc"Hello"); /輸出Hello World C# 解析配置文件內(nèi)容 System.Configuration 1. 創(chuàng)建配置節(jié)類 必須創(chuàng)建繼承自ConfigurationSection的對象才能進行配置數(shù)據(jù)讀寫操作,ConfigurationSe
19、ction提供了索引器用來獲取和設置配置數(shù)據(jù),需要注意的是擁有ConfigurationProperty特性的屬性才會被存儲,并且名稱要保持大小寫完全一致,如下面的代碼中,所有的"id"必須保持一樣。 復制代碼 代碼如下:class ConfigSectionData : ConfigurationSection ConfigurationProperty("id") public int Id get return (int)this"id" set this"id" = value; Configuration
20、Property("time") public DateTime Time get return (DateTime)this"time" set this"time" = value; 2. 創(chuàng)建配置文件操作對象 復制代碼 代碼如下:Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); ConfigSectionData data = new ConfigSectionData(); data.Id
21、 = 1000; data.Time = DateTime.Now; config.Sections.Add("add", data); config.Save(ConfigurationSaveMode.Minimal); 上面的例子是操作 app.config,在根節(jié)點(configuration)下寫入名稱為"add"的配置數(shù)據(jù)。 復制代碼 代碼如下:<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSe
22、ctions> <section name="add" type="ConsoleApplication1.ConfigSectionData, . /> </configSections> <add id="1000" time="02/18/2006 21:51:06" /> </configuration> 需要注意的 VS2005 在IDE模式下會將信息寫入 *.vshost.exe.config,并且在程序關閉時覆寫該文件,因此您可能看不到您寫入的配置數(shù)據(jù),只要
23、在資源管理其中執(zhí)行 *.exe 文件,您就可以在 *.exe.config 文件中看到結(jié)果了。 如果我們需要操作非缺省配置文件,可以使用ExeConfigurationFileMap對象。 復制代碼 代碼如下:ExeConfigurationFileMap file = new ExeConfigurationFileMap(); file.ExeConfigFilename = "test.config" Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, Configu
24、rationUserLevel.None); ConfigSectionData data = new ConfigSectionData(); data.Id = 1000; data.Time = DateTime.Now; config.Sections.Add("add", data); config.Save(ConfigurationSaveMode.Minimal); 如果我們不希望在根節(jié)點下寫入配置數(shù)據(jù),可以使用ConfigurationSectionGroup對象。 復制代碼 代碼如下:ExeConfigurationFileMap file = new
25、ExeConfigurationFileMap(); file.ExeConfigFilename = "test.config" Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None); ConfigSectionData data = new ConfigSectionData(); data.Id = 1000; data.Time = DateTime.Now; config.SectionGroups.Add(
26、"group1", new ConfigurationSectionGroup(); config.SectionGroups"group1".Sections.Add("add", data); config.Save(ConfigurationSaveMode.Minimal); 下面就是生成的配置文件。 復制代碼 代碼如下:<?xml version="1.0" encoding="utf-8"?> <configuration> <configSection
27、s> <sectionGroup name="group1" type="System.Configuration.ConfigurationSectionGroup, . > <section name="add" type="ConsoleApplication1.ConfigSectionData, . /> </sectionGroup> </configSections> <group1> <add id="1000" time=&q
28、uot;02/18/2006 22:01:02" /> </group1> </configuration> 3. 讀取配置文件 復制代碼 代碼如下:ExeConfigurationFileMap file = new ExeConfigurationFileMap(); file.ExeConfigFilename = "test.config" Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUser
29、Level.None); ConfigSectionData data = config.SectionGroups"group1".Sections"add" as ConfigSectionData; /ConfigSectionData data = config.Sections"add" as ConfigSectionData; / 從根節(jié)讀取 if (data != null) Console.WriteLine(data.Id); Console.WriteLine(data.Time); 4. 寫配置文件 在寫入 C
30、onfigurationSectionGroup 和 ConfigurationSection 前要判斷同名配置是否已經(jīng)存在,否則會寫入失敗。 另外如果配置文件被其他Configuration對象修改,則保存會失敗,并拋出異常。建議采用Singleton模式。 復制代碼 代碼如下:ExeConfigurationFileMap file = new ExeConfigurationFileMap(); file.ExeConfigFilename = "test.config" Configuration config = ConfigurationManager.Open
31、MappedExeConfiguration(file, ConfigurationUserLevel.None); ConfigSectionData data = new ConfigSectionData(); data.Id = 2000; data.Time = DateTime.Now; ConfigurationSectionGroup group1 = config.SectionGroups"group1" if (group1 = null) config.SectionGroups.Add("group1", new Configu
32、rationSectionGroup(); ConfigurationSection data = group1.Sections"add" as config; if (add = null) config.SectionGroups"group1".Sections.Add("add", data); else group1.Sections.Remove("add"); group1.Sections.Add("add", data); / 或者直接修改原配置對象,前提是類型轉(zhuǎn)換要成功。
33、/ConfigSectionData configData = add as ConfigSectionData; /configData.Id = data.Id; /configData.Time = data.Time; config.Save(ConfigurationSaveMode.Minimal); 5. 刪除配置節(jié) 復制代碼 代碼如下:刪除ConfigurationSectionGroup config.SectionGroups.Remove("group1"); /config.SectionGroups.Clear(); config.Save(Con
34、figurationSaveMode.Minimal); 刪除ConfigurationSection config.Sections.Remove("add1"); /config.Sections.Clear(); if (config.SectionGroups"group1" != null) config.SectionGroups"group1".Sections.Remove("add2"); /config.SectionGroups"group1".Sections.Clear
35、(); config.Save(ConfigurationSaveMode.Minimal); 6. 其他 可以使用 ConfigurationManager.OpenMachineConfiguration() 來操作 Machine.config 文件。 或者使用 System.Web.Configuration 名字空間中的 WebConfigurationManager 類來操作 ASP.net 配置文件。 ConfigurationManager還提供了AppSettings、ConnectionStrings、GetSection()等便捷操作。 7. 使用自定義類 可以使用自定義
36、類,不過需要定義一個轉(zhuǎn)換器。 復制代碼 代碼如下:using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.ComponentModel; / 要寫入配置文件的自定義類 class CustomData public CustomData(string s) this.s = s; private string s; public string S get return
37、 s; set s = value; / 自定義的轉(zhuǎn)換器(演示代碼省略了類型判斷) class CustomConvert : ConfigurationConverterBase public override bool CanConvertFrom(ITypeDescriptorContext ctx, Type type) return (type = typeof(string); public override object ConvertTo(ITypeDescriptorContext ctx, CultureInfo ci, object value, Type type) r
38、eturn (value as CustomData).S; public override object ConvertFrom(ITypeDescriptorContext ctx, CultureInfo ci, object data) return new CustomData(string)data); class ConfigSectionData : ConfigurationSection ConfigurationProperty("id") public int Id get return (int)this"id" set thi
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 醫(yī)藥廢物處置合同范本
- 獸醫(yī)樣品郵寄合同范本
- 叉車工合同范例
- 廠房分紅合同范例
- 印染勞務派遣合同范例
- 個人競聘述職報告
- 財經(jīng)法規(guī)與會計職業(yè)道德(第5版) 習題答案 王紅云
- 業(yè)主停車安全合同范本
- 幕墻合同范本
- 內(nèi)銷返利合同范例
- 巖石力學與工程課后習題與思考解答
- 《民族樂器分類二》教案
- API520-安全閥計算PART1(中文版)
- 生產(chǎn)車間管理制度辦法
- 機電企業(yè)管理導論第1章課件
- 水平一足球全冊教案
- 蘇教版科學二年級下冊全冊教案
- 約束評分標準
- GB/T 28799.2-2020冷熱水用耐熱聚乙烯(PE-RT)管道系統(tǒng)第2部分:管材
- GB 16780-2021水泥單位產(chǎn)品能源消耗限額
- 全面推進依法行政課件
評論
0/150
提交評論