Managing Your ASP.NET Application[2]->Retrieving Configuration
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.
| C# | VB | |
CustomConfigSettings settings = (CustomConfigSettings)ConfigurationManager.GetSection("customConfig");
if (settings.Enabled) {
// Do something here.
}
|
||
Note: the runtime API will return a read-only instance of the configuration section.
Using Application Settings
Configuration files are perfectly suited for storing custom application settings, such as database 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 web service URLs for an application
<configuration> <appSettings> <add key="currencyService" value="http://www.microsoft.com/services/currencyService.asmx" /> <add key="creditCardValidationService" value="http://www.microsoft.com/services/cc.asmx" /> </appSettings> </configuration>
The ConfigurationManager object exposes a special AppSettings property that you can use to retrieve these settings:
| C# | VB | |
String service = ConfigurationManager.AppSettings["currencyService"];
|
||
The following sample illustrates this technique.
Using Connection Strings
Like general application settings, ASP.NET provides a configuration section specifically for storing database connection strings, used by ADO.NET. The following example shows a <connectionString> configuration section for an application that uses the Northwind sample database.
<configuration> <connectionStrings> <add name="northwind" connectionString="server=(local)\SQLExpress;database=Northwind;Integrated Security=SSPI" providerName="System.Data.SqlClient" /> </connectionStrings> </configuration>
The ConfigurationManager object exposes a special ConnectionStrings property that you can use to retrieve these settings.
| C# | VB | |
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["northwind"].Name);
|
||
If the providerName property of each connection string is set, you can use it to create and connect to the database generically using ADO.NET provider factories, rather than using code specific to the type of ADO.NET provider. The following sample illustrates this technique.


浙公网安备 33010602011771号