任意の web.config ファイルのカスタム セクションを変更する必要がある WinForm 派生アプリケーション (ASP.NET Web アプリケーションではないことに注意してください) があります。例として、私の web.config が次のような場合:
<?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>
maxRequestLength
たとえば、これを行うとうまくいくので、いくつかのデフォルトパラメータを簡単に変更できます。
//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);
}
問題は、カスタム セクションを変更しようとしたときです。Var1
パラメータの値をで書き換えたい場合はvalue2
、次のようにします。
System.Configuration.ConfigurationSection genParams = config.GetSection("MyConfigSection/GeneralParameters");
を返しnull
、 just で呼び出すと、次のMyConfigSection
例外が発生します。
MyConfigSection の構成セクション ハンドラーの作成中にエラーが発生しました: アセンブリ 'System.Web、Version=4.0.0.0、Culture=neutral、PublicKeyToken=N' から型 'MyWebApp.Configuration' を読み込めませんでした。
その「構成セクションハンドラー」を追加するには、ここで何をすればよいですか?