ahmd0
ahmd0

Reputation: 17313

How to modify custom sections of the web.config file, from a generic .NET application?

I have a WinForm derived application (note NOT an ASP.NET web application) from where I need to modify a custom section of an arbitrary web.config file. As an example, if my web.config is something like this:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <!-- General web.config stuff follows -->
  <system.web>
    <httpRuntime executionTimeout="110" maxRequestLength="1024" requestValidationMode="2.0" />
  </system.web>

  <MyConfigSection>
    <GeneralParameters>
      <param key="Var1" value="value1" />
    </GeneralParameters>
  </MyConfigSection>

</configuration>

I can easily modify some default parameter, say, for maxRequestLength I'd do this and it would work:

//Path to the web.config file
string strWebConfigFile = @"C:\My files\web.config";

//Convert absolute path to virtual
var configFile = new FileInfo(strWebConfigFile);
var vdm = new VirtualDirectoryMapping(configFile.DirectoryName, true, configFile.Name);
var wcfm = new WebConfigurationFileMap();
wcfm.VirtualDirectories.Add("/", vdm);

//Open web.config file
System.Configuration.Configuration config = 
    System.Web.Configuration.WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");
if (config != null)
{
    System.Configuration.ConfigurationSection system_web = 
        config.GetSection("system.web/httpRuntime");

    PropertyInformation pi = system_web.ElementInformation.Properties["maxRequestLength"];

    pi.Value = 1234;    //Set new value

    //Save
    config.Save(ConfigurationSaveMode.Modified);
}

The issue is when I try to modify my custom section. Say, if I wanted to rewrite Var1 parameter's value with value2, the following:

System.Configuration.ConfigurationSection genParams = config.GetSection("MyConfigSection/GeneralParameters");

returns null and if I call it with just MyConfigSection, it gives me this exception:

An error occurred creating the configuration section handler for MyConfigSection: Could not load type 'MyWebApp.Configuration' from assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=N'.

What shall I do here to add that "configuration section handler"?

Upvotes: 0

Views: 651

Answers (1)

Jim W
Jim W

Reputation: 5016

You have to open it up with XmlDocument, and work with it, sorry. That is how we cracked this nut - sorry I'm not at liberty to give you the code.

Upvotes: 1

Related Questions