Retrieving ConfigurationASP.NET allows developers to access configuration settings from within an application either by exposing configuration settings directly (as strongly typed properties) or by using general configuration APIs. The following sample shows a page that accesses the <browserCaps> configuration section using the Browser property of the System.Web.HttpRequest class. This is a hash table of attributes that reflect the capabilities of the browser client that is currently accessing the page. The actual <browserCaps> section data is included in the machine.config file.
In addition to accessing configuration settings, as demonstrated above, developers also can use the System.Configuration.ConfigurationSettings class to retrieve the data for any arbitrary configuration section. Note that the particular object returned by ConfigurationSettings depends on the section handler mapped to the configuration section (see IConfigurationSectionHandler.Create). The following code demonstrates how you can access the configuration data exposed for a <customconfig> section. In this example, it is assumed that the configuration section handler returns an object of type CustomConfigSettings with the property Enabled.
Dim config As CustomConfigSettings = CType(ConfigurationSettings("customconfig"), CustomConfigSettings)
If config.Enabled = True Then
' Do something here.
End If
VB
Using Application SettingsConfiguration files are perfectly suited for storing custom application settings, such as database connection strings, file paths, or remote XML Web service URLs. The default configuration sections (defined in the machine.config file) include an <appSettings> section that may be used to store these settings as name/value pairs. The following example shows an <appSettings> configuration section that defines database connection strings for an application.
<configuration>
<appSettings>
<add key="pubs" value="server=(local)\NetSDK;database=pubs;Trusted_Connection=yes" />
<add key="northwind" value="server=(local)\NetSDK;database=northwind;Trusted_Connection=yes" />
</appSettings>
</configuration>
Dim dsn As String = ConfigurationSettings.AppSettings("pubs")
VB
The following sample illustrates this technique.
|