Accessing Configuration Files Programmatically

for RuBoard

Because the Web configuration files are XML documents, you could use the XML-handling objects (discussed in Chapter 10, "Using XML") to store and retrieve information in Web.Config and Machine.Config. This might be useful when you want to store application-specific information in Web.Config, such as a database connection string.

However, you don't need to go to the trouble of parsing Web.Config to store and retrieve custom values from the file ”there is an easier way. To store application-specific settings in Web.Config, simply create a section called appSettings and add the settings you want as key/value pairs in that section.

In the following example, the connection string is given the key "pubsdata"; the value of the setting is the familiar ADO connection string.

 <configuration>     <system.web>         <customErrors mode="Off" />     </system.web>     <appSettings>       <add key="pubsdata" value="SERVER=localhost;DATABASE=pubs;UID=sa;PWD=mypass;" />     </appSettings> </configuration> 

Note that you aren't limited to storing database connection strings in appSettings, but appSettings is a reasonable solution to the common problem of where to store connection string data without sticking it into a constant in your code or using a conventional include file.

To retrieve the custom application setting, you use the AppSettings collection contained in the ConfigurationSettings object. This object, a member of the System.Configuration namespace in the .NET framework, enables you to access the values stored in Web.Config by their key. So, for example, to retrieve the pubsdata value specified in the previous example, you'd use the expression

 Response.Write(ConfigurationSettings.AppSettings["eqguild"]); 

Note that it's not necessary to create an instance of the ConfigurationSettings object. As with other objects such as Page and Response, a single instance of ConfigurationSettings is always available to code that executes in your ASP.NET page.

for RuBoard


C# Developer[ap]s Guide to ASP. NET, XML, and ADO. NET
C# Developer[ap]s Guide to ASP. NET, XML, and ADO. NET
ISBN: 672321556
EAN: N/A
Year: 2005
Pages: 103

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net