Reading Application Settings from a File

The Web.config file defines configuration settings, and can be edited or established during development, deployment, or after deployment.

Web.config files are stored in XML format for easy manipulation. Applications can contain any amount of Web.config files, and each file is applied to its own directory and child directories. Changes to Web.config do not require a server reboot. Review typical Web.config structure below:

<configuration>
	<configSections>
		<sectionGroup>
		</sectionGroup>
	</configSections>

	<system.web>
	</system.web>

	<connectionStrings>
	</connectionStrings>

	<appSettings>
	</appSettings>
</configuration>

Review another example of typical structure and content:

<system.web
	<compilation
		debug="true" strict="true" explicit="true"
batch="true"
		optimizeCompilations="true" batchTimeout="700"
		maxBatchSize="900" maxBatchGeneratedFileSize="900"
		numRecompilesBeforeAppRestart="10"
defaultLanguage="c#"
		targetFramework="4.0" assemblyPostProcessorType="">
	<assemblies>
		<add assembly="System, Version=2.0.9000.0, Culture=neutral,
			PublicKeyToken=b01a5c544934e079"/>
	</assemblies>
</compilation>
</system.web>

It contains compilation settings, page settings, custom error settings, location settings, session state and view state settings, HttpHandler settings, authentication settings, and much more.

ACCESSING AND MODIFYING

The example below reads Compilation values from the Web.config file:

//System.Configuration object initialization
Configuration config =
WebConfigurationManager.OpenWebConfiguration("~/");
//Retrieve required section of web.config file through config object
CompilationSection compilation =
	(CompilationSection)config.GetSection("system.web/compilation");
//Access web.config properties
Response.Write("Debug:"+compilation.Debug+"
""+ "Language:"+compilation.DefaultLanguage);

The following example updates values for compilation settings:

Configuration config =
WebConfigurationManager.OpenWebConfiguration("~/");
CompilationSection compilation =
	(CompilationSection)config.GetSection("system.web/compilation");

//Update new values
compilation.Debug = true;

//save changes through the Save() method of configuration object
if (!compilation.SectionInformation.IsLocked)
{
config.Save();
Response.Write("New Compilation Debug"+compilation.Debug);
}
else
{
Response.Write("Config could not be saved.");
}