通过编程访问任意web.config文件-无法访问appSettings(app.config文件可用)

6

我这样访问配置文件:

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

它可以很好地处理任何 .exe.config 文件,但不能处理任何 web.config 文件。
注意:我不是在尝试访问当前应用程序的 web.config,而是尝试修改任意路径下的 web.config。
(我已经尝试使用 WebConfigurationManager 替换 ConfigurationManager,但结果相同)
异常由 AppSettings 属性访问器引发 - 尝试获取“appSettings”部分并将其转换为 AppSettingsSection 当然会出现相同的异常。无论哪种方法,这里都是它:
System.InvalidCastException: Unable to cast object of type 'System.Configuration.DefaultSection' to type 'System.Configuration.AppSettingsSection'.

我显然进行了搜索,但只发现人们访问“当前 Web 应用程序”的 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();

在这里我正在使用OpenMappedMachineConfiguration,它似乎是用于machine.config的,然而我找不到打开任意web.config文件的其他方法 - 有人知道吗?


那么,如果您将web.config的名称更改为web.exe.config,那么一切都会按预期工作吗? - Ben Robinson
哦,不对,问题还是一样的。可能是因为web.exe(或者我也试过test.exe.config)不存在...不,也不是这个原因。让我看看我的配置文件之间的差异... - Kieren Johnstone
[最新编辑:.exe.config 我正在使用另一种有效的方法] - Kieren Johnstone
1个回答

10

我犯了一个错误 - 当打开web.config文件时,我可以很好地使用OpenMappedExeConfiguration

            var map = new ExeConfigurationFileMap();
            map.ExeConfigFilename = configPath;
            var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接