以编程方式访问任意web.config - 无法访问appSettings(app.config很好)

Kie*_*one 6 .net c# configuration

我正在访问配置文件:

var map = new ConfigurationFileMap(configPath);
var config = ConfigurationManager.OpenMappedMachineConfiguration(map);
config.AppSettings.Settings.Add("SomeSetting", "SomeValue");
Run Code Online (Sandbox Code Playgroud)

它适用于任何.exe.config文件,但不适用于任何web.config.

注意:我没有尝试访问当前应用程序的web.config,我试图在任意路径中修改web.config.

(我试过WebConfigurationManager而不是ConfigurationManager,但它给出了相同的结果)

AppSettings属性访问者抛出异常- 尝试GetSection("appSettings")并将其AppSettingsSection转换为相同的异常.无论哪种方式,这里是:

System.InvalidCastException: Unable to cast object of type 'System.Configuration.DefaultSection' to type 'System.Configuration.AppSettingsSection'.
Run Code Online (Sandbox Code Playgroud)

我显然已经四处搜索,但发现只有人访问'当前网络应用'的web.config或使用XmlDocument/ XDocument.

我的猜测是.exe.config文件会自动获得一些推断的configSections类型信息,这意味着它正确地知道如何处理appSettings.但是我不知道为什么,根据文件名,它不适用于web.config.


啊.对于app.config,我正在使用OpenExeConfiguration:

// works fine for .exe.config
var config = ConfigurationManager.OpenExeConfiguration("some-assembly-here.exe");
config.AppSettings.Settings.Add("SomeSetting", "SomeValue");
config.Save();
Run Code Online (Sandbox Code Playgroud)

在这里我使用的OpenMappedMachineConfiguration似乎是machine.config,但是我看不到打开任意web.config文件的另一种方式 - 任何人?

Kie*_*one 10

我的错误 - OpenMappedExeConfiguration打开web.config文件时我可以正常使用:

            var map = new ExeConfigurationFileMap();
            map.ExeConfigFilename = configPath;
            var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
Run Code Online (Sandbox Code Playgroud)