加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 以编程方式访问任意web.config – 无法访问appSettings(ap

发布时间:2020-12-15 04:17:38 所属栏目:百科 来源:网络整理
导读:我正在访问配置文件: var map = new ConfigurationFileMap(configPath);var config = ConfigurationManager.OpenMappedMachineConfiguration(map);config.AppSettings.Settings.Add("SomeSetting","SomeValue"); 它适用于任何.exe.config文件,但不适用于任
我正在访问配置文件:
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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读