我正在访问配置文件:
- 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属性访问器抛出异常 – 尝试GetSection(“appSettings”)并将其转换为AppSettingsSection当然gievs相同的异常.无论哪种方式,这里是:
- System.InvalidCastException: Unable to cast object of type 'System.Configuration.DefaultSection' to type 'System.Configuration.AppSettingsSection'.
我显然已经四处寻找,但发现只有人访问’当前网络应用’的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文件时我可以正常使用OpenMappedExeConfiguration:
- var map = new ExeConfigurationFileMap();
- map.ExeConfigFilename = configPath;
- var config = ConfigurationManager.OpenMappedExeConfiguration(map,ConfigurationUserLevel.None);