【问题标题】:How prevent to create a .exe.config in a Windows Forms Application build (Visual Studio Community 2019 - C#)如何防止在 Windows 窗体应用程序构建中创建 .exe.config (Visual Studio Community 2019 - C#)
【发布时间】:2019-12-22 15:28:56
【问题描述】:

我正在使用目标框架 .NET 2.0 处理遗留项目(Windows 窗体应用程序)。目标是构建一个不依赖于任何配置文件的.exe 文件(特别是不依赖于.exe.config,因为应用程序不需要此配置文件中的任何内容)。

项目特点:

Application:
Targe framework: .NET Framework 2.0
Output type: Windows Application
Auto-generate binding redirecs: Not enabled

Build:
Platform target: Any CPU

Visual Studio Community 2019, version 16.1.3

该解决方案有一个 app.config 文件,我试图删除它,但由于某种原因它似乎仍保留在项目中。当我说 似乎 留在项目中是因为我遵循以下步骤:

  1. 在解决方案资源管理器中,右键单击App.config,然后单击从项目中排除
  2. 重建项目,仍然生成.exe.config
  3. 再次在解决方案资源管理器中 > 添加 > 新项目,当我尝试添加名称为 App.config 的应用程序配置文件时,VS 显示此消息:名称为“App.config”的文件已存在.要更换吗?

(我也试过右击App.config,然后点击删除选项)

这似乎表明配置文件没有有效地从项目中删除,因此仍然会生成.exe.config

另外,我检查了这个post,并尝试更改文件属性(构建操作复制到输出目录等)但.exe.config文件保留在构建中。

最后,我尝试(可能更多是绝望的尝试)取消选中 自动生成绑定重定向,这会阻止.exe.config 的生成,但.exe 运行不正常.

作为附加信息,.exe.config 的内容是:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Company.Afis.ImageContainer" publicKeyToken="97cac07b8409e999" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.5.0.1827" newVersion="2.5.0.1827" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

我检查过的其他帖子:

如果需要任何其他信息,请告诉我更新。

【问题讨论】:

  • 您可以禁用程序集绑定并使用AppDomain.AssemblyResolve
  • pdb 文件怎么样?你有他们禁用吗?我问是因为我不确定你为什么要禁用 exe.config-files。要让 clean Bin 文件夹里面只有一个 exe?其他文件是否会导致问题?哪个问题?
  • @Reza Aghaei 我正在检查,谢谢。 @Sinatr,我已启用/禁用调试信息,但它不影响 .exe.config。想法是拥有一个不依赖于任何其他文件的.exe 文件,所以是的.. 拥有一个干净的Bin 文件夹。至于问题,如果我删除 .exe.config 文件,.exe 将无法正常运行。

标签: c# visual-studio winforms build


【解决方案1】:

禁用程序集绑定重定向的自动生成,而是处理当前AppDomain.CurrentDomainAssemblyResolve 事件并在事件处理程序中加载请求的程序集。

  • 禁用自动生成程序集绑定重定向

    右键单击项目,选择属性,然后在项目属性页面的第一个选项卡(应用程序选项卡)中,取消选中自动生成绑定重定向。你可以通过编辑项目文件并设置&lt;AutoGenerateBindingRedirects&gt;false&lt;/AutoGenerateBindingRedirects&gt;来做同样的事情。

  • 处理 AssemblyResolve 事件

    您应该在运行时尝试加载程序集之前添加事件处理程序。比如Program类的静态构造函数中。例如,在下面的代码中,我假设应用程序正在寻找MyAssembly,我在应用程序的文件夹中将它作为MyAssembly2.dll

    static Program()
    {
        AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
    }
    private static Assembly CurrentDomain_AssemblyResolve(object sender, 
        ResolveEventArgs args)
    {
        if (new AssemblyName(args.Name).Name == "MyAssembly")
            return Assembly.LoadFrom(
                Path.Combine(Application.StartupPath, "MyAssembly2.dll"));
        throw new Exception();
    }
    

【讨论】:

    猜你喜欢
    • 2021-08-12
    • 2023-01-18
    • 1970-01-01
    • 1970-01-01
    • 2020-02-01
    • 1970-01-01
    • 2021-04-01
    • 2016-09-06
    • 2015-02-18
    相关资源
    最近更新 更多