【问题标题】:C# Opening a configuration file from an arbitrary locationC# 从任意位置打开配置文件
【发布时间】:2016-05-06 02:43:18
【问题描述】:

在:

Using ConfigurationManager to load config from an arbitrary location 我找到了似乎是一个解决方案。我正在处理的项目使用网络上的 appSettings.config 文件位置。但是当我尝试使用引用的代码时:

 System.Configuration.ConfigurationFileMap fileMap = new ConfigurationFileMap("Z:\Settings\appSettings.config"); //Path to your config file

 System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(fileMap);

到目前为止一切顺利。 appSettings.config 文件如下所示:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="Environment" value="Development" />
  </appSettings>
</configuration>

然后我得到以下这一行:

var settings = configuration.AppSettings.Settings;

或任何使用它的东西,比如 Settings.Count,我得到一个无效的投射异常。基本上,我如何从中获得“环境”的价值?

【问题讨论】:

  • var environment = configuration.AppSettings["Environment"]
  • 看起来appSettings 标签没有映射到AppSettingsSection 对象,而是映射到DefaultSection。不知道为什么,如果我得出任何结论,我会回复你。

标签: c# configurationmanager


【解决方案1】:

我发现这是可行的:

System.Configuration.ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();

fileMap.ExeConfigFilename = @"Z:\appSettings.config"; //Path to your config file

System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); // OpenMappedMachineConfiguration(fileMap);
return configuration.AppSettings.Settings["Environment"].Value;

这可以正常工作。

【讨论】:

  • 谢谢 :) 尝试了很多其他解决方案,但都失败了。
猜你喜欢
  • 1970-01-01
  • 2016-12-29
  • 2013-12-05
  • 2014-06-05
  • 2010-09-05
  • 1970-01-01
  • 2014-05-03
  • 2021-11-23
相关资源
最近更新 更多