C#程序的配置文件,使用的最多的是appSettings 下的<add key="Interval" value="30"/>,這種配置單項的很方便,但是配置集合就不方便了(當然你可以用逗號分隔,key=key1,key2,key3……但是你還是不知道有多少個集合).現在給出解決方案.
需求:程序超級管理員采用這種設置方式,在app.config中配置的方式,可以配置多個.登陸成功后,讀取config,看我是不是超級管理員.
(當然,這個需求是很扯淡的,因為我是為了舉例子,編造的,哇哈哈哈)
1.下載ConfigurationSectionDesigner_2.0.1.7.vsix,安裝;
2.重新打開VS,新建測試工程WindowsFormsApplication2;
3.在工程上右鍵,添加新建項,選在ConfigurateSectionDesiger,命名為ConfigurateSectionDesiger1;
4.雙擊ConfigurateSectionDesiger1,打開他的設計頁面,點擊"工具箱";
5.拖一個Configuration Section到頁面上,命名為UserSection;
6.點擊UserSection的Elements,新增Element,命名為Users
7.工具箱拖一個ConfigurationElementCollection到頁面,命名為UserCollection;
8.點擊UserSection中的User的屬性,選擇Type 為: UserCollection,此時UserSection和UserCollection出現箭頭連接;
9.工具箱,拖動一個Configuration Element,命名為User.為User增加Attributes,ID,Name,Gender,Pwd,並指定每個attributes的type為string,將ID的Is key 設置為true.
10.設置UserCollection的Item Type為User.
11.查看ConfigurationSectionDesigner1.csd下,有個文件ConfigurationSectionDesigner1.csd.config
12.打開ConfigurationSectionDesigner1.csd.config,將configSections和userSection標簽中的內容復制到App.config的configuration節點中.
<configSections> <section name="userSection" type="WindowsFormsApplication2.UserSection, WindowsFormsApplication2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/> </configSections> <userSection xmlns="urn:WindowsFormsApplication2"> <!-- This is just a minimal sample configuration file that shows how to declare the configuration sections. Because an XML Schema Definition (XSD) is generated for each configuration section, it should be trivial to edit these files because you have IntelliSense on the XML definition. --> </userSection>
13.現在已經配置好了,在app.config中,userSection節點下,敲一下"<",就會出現users的智能提示,在users下敲"<",會出現user的提示,同時user並有iD,Name,Gender,Pwd這些屬性
14.讀取方法
var section = (UserSection)System.Configuration.ConfigurationManager.GetSection("userSection");
for (int i = 0; i < section.Users.Count; i++)
{
string ID = section.Users[i].ID;
string name = section.Users[i].Name;
string Pwd = section.Users[i].Pwd;
string Gender = section.Users[i].Gender;
}
注意:app.config中的configSections節點必須放在開始.即是放在configuration節點最開始
PS:這個文章只是利用工具插件,自動生成結構,然后靠在app.config里面配置反射,其實工具那段是可以通過編碼來實現的.參看下個文章.
