【问题标题】:app.config inside Visual Studio Extension?Visual Studio 扩展中的 app.config?
【发布时间】:2019-12-09 15:53:15
【问题描述】:

我创建了一个表示 Visual Studio 项目向导(vsix 包)的 Visual Studio 扩展。我正在尝试连接 log4net,但没有成功。我已将问题归结为我的 app.config 未正确加载。

我已将此添加到我的 Visual Studio 扩展中的 app.config 中:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="test" value="hello world"/>
  </appSettings>
</configuration>

在我的 IWizard 实现中,我添加了这行代码:

var test = System.Configuration.ConfigurationManager.AppSettings["test"];

但是,上面的test变量在调试时总是为空。

我已经验证了这些事情:

  • App.config 设置为 Build Action: Content
  • App.config 设置为复制到输出目录:始终复制
  • App.config 设置为包含在 VSIX 中:True
  • App.config 文件存在于我的C:\Users\&lt;user&gt;\AppData\Local\Microsoft\VisualStudio\16.0_...\Extensions\&lt;Name&gt;\&lt;Company&gt;\1.0 文件夹中

我错过了什么?如果在 VSIX 扩展开发中不允许 App.config,您将如何连接 log4net?

【问题讨论】:

标签: visual-studio-extensions vsix


【解决方案1】:

我错过了什么?如果在 VSIX 中不允许 App.config 扩展开发,你将如何连接 log4net?

App.Config 文件在构建过程中被复制并重命名为 .exe.config,因此只有可执行文件才能直接使用 ConfigurationManager 拥有和使用“App.Config”文件。 通常,VSIX 项目会生成一个加载到 Visual Studio 可执行文件 (devenv.exe) 中的 DLL,因此您的项目直接使用 ConfigurationManager 只能从 devenv.exe.config(文件夹 C:\Program Files (x86 )\Microsoft Visual Studio 16.0\Common7\IDE)。

当我在 vsix 项目中使用我唯一的 app.config 文件对其进行测试时,该项目似乎无法仅从默认的 devenv.exe.config 获取我的自定义文件的值,它只包含两个值 TestProjectRetargetTo35AllowedEnableWindowsFormsHighDpiAutoResizing。这意味着在任何情况下,它都会从 devenv.exe.config 中获取值。

解决方案

1#。您只需在devenv.exe.config 文件中定义新密钥,即可直接从文件中获取。

 <appSettings>
    <add key ="TestProjectRetargetTo35Allowed" value ="true"/>
    <add key ="EnableWindowsFormsHighDpiAutoResizing" value ="true"/>
      insert new key here
  </appSettings>

2#。你可以通过代码获取这个app.config,直接从中获取key的值。

ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = @"xxxxxxxx"; // the path of the custom app.config
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
var test = config.AppSettings.Settings["test"].Value;

另外,我推荐solution2更好,更容易解决您的问题。 希望对你有帮助。

【讨论】:

  • 虽然我对答案不满意(因为我必须以某种方式将配置注入其他库) - 这是正确的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-11
  • 2019-02-09
  • 1970-01-01
  • 1970-01-01
  • 2013-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多