app.config 在 Visual Studio 内扩展?

app.config inside Visual Studio Extension?

我创建了一个 Visual Studio 扩展,表示 Visual Studio 项目向导(vsix 包)。我正在尝试连接 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变量在调试的时候总是null。

我已经验证了这些事情:

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

What am I missing? And if App.config is not allowed within VSIX extension development, how would you go about wiring up log4net?

App.Config 文件在构建期间被复制并重命名为 .exe.config,因此只有可执行文件可以直接使用 ConfigurationManager 拥有和使用 "App.Config" 文件。 通常,VSIX 项目会生成一个 DLL 并加载到 Visual Studio 可执行文件 (devenv.exe) 中,因此您的项目直接使用 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 并直接从中获取键的值。

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更好更容易解决你的问题。 希望对你有帮助。