當我們程序中使用配置文件時,Asp.net中使用是Web.config,WinForm和Console中使用是App.config。通常用的最多是AppSettings節,有的時候覺得不夠用,另一選擇就是自己實現SectionHandler,來實現自定義配置節。看下面的示例AppSettings節:
<appSettings> <add key="source1user" value="user" /> <add key="source1password" value="pass" /> </appSettings>
對於上面兩個配置項,要寫個自定義配置類是不是很麻煩,我們還有另一種簡單實現方法,使用 SingleTagSectionHandler
MSDN是這麼描述的:Handles configuration sections that are represented by a single XML tag in the .config file".
下面來看一下:
<configSections> <section name="remoteDataSource" type="System.Configuration.SingleTagSectionHandler" /> </configSections> <remoteDataSource username="user" password="pass" url="http://remote/" />
代碼中這樣訪問:
[Test] public void TestConfig() { Hashtable remoteDataSource = (Hashtable)ConfigurationManager.GetSection("remoteDataSource"); string username = (string)remoteDataSource["username"]; string password = (string)remoteDataSource["password"]; string url = (string)remoteDataSource["url"]; Assert.AreEqual("user", username); Assert.AreEqual("pass", password); }