組態檔

組態檔是一個xml文件,提供了 System [.Web] .Configuration 這個管理功能的NameSpace,要使用它,需要參考 System.configuration.dll。

asp.net

在asp.net裡的組態檔是 web.config,使用System.Web.Configuration.WebConfigurationManager

WinForm

在WinForm是App.Config(ExeName.exe.config),使用 System.Configuration.ConfigurationManager

使用方式

Web.config:
<appSettings>
    <add key="appKey" value="I am a appSettings"/>        
</appSettings>

Code: WebConfigurationManager.AppSettings["appKey"]; WebConfigurationManager.ConnectionStrings["connKey"].ConnectionString;

自訂組態

Web.config:
<configSections>
    <section name="customerSection" type="System.Configuration.NameValueSectionHandler" allowLocation="true" allowDefinition="Everywhere"/>

</configSections>

<customerSection>
    <add key="customerKey" value="I am a customer"/>
</customerSection>

Code: NameValueCollection config = WebConfigurationManager.GetSection("customerSection") as NameValueCollection; Console.WriteLine(string.Format("customerSection:{0}", config["customerKey"]));

組態轉換

一般組態

<appSettings>
    <add key="emailAccount" value="[email protected]"/>
    <add key="emailPassword" value="123456"/>
</appSettings>

替換組態

<appSettings>
<add key="emailAccount" value="[email protected]" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>    
</appSettings>

參考

自訂組態 http://msdn.microsoft.com/zh-tw/library/system.configuration.configurationelement(v=vs.110).aspx

組態轉換 http://msdn.microsoft.com/zh-tw/library/dd465326.aspx