Writing Configuration Files

Monday, November 14, 2005

2.0 provides ability to modify configuration files. As you might expect, it is difficult to modify a configuration file in a locked down environment. As an example, the following code tries to change the compilation section to disable batch compilation and enable debugging.

protected void ModifyConfig_Click(object sender, EventArgs e)

{

    Configuration config;

    config = WebConfigurationManager.OpenWebConfiguration("~");

 

    CompilationSection compilation;

    compilation = config.GetSection("system.web/compilation")

       as CompilationSection;

 

    compilation.Batch = false;

    compilation.Debug = true;

 

    config.Save();             

}

Two problems you’ll quickly run into:

The code throws an exception under medium trust because the code needs read privileges on all of the configuration files from which it inherits settings. Medium trust only grants file IO permissions in the application’s virtual directory.

The code will need write access to the directory where the configuration file exists – not just write access to the file itself. If you watch the file system with a tool like FileMon, you’ll see the runtime create a brand new .config file with a temporary name. I imagine this approach prevents change notifications from recycling app domains too many times and let's the runtime "swap" in the new settings with a delete and rename operation.


Comments
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!