首页 > 解决方案 > .NET 5 未编译为单个文件可执行文件

问题描述

我在通过 Visual Studio 调试时尝试将我的 .NET 5 应用程序编译为单个可执行文件时遇到问题。

我的 .csproject 文件在下面。

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net50</TargetFramework>
    <AutoGenerateBindingRedirects>false</AutoGenerateBindingRedirects>
    <RuntimeIdentifier>win-x64</RuntimeIdentifier>
    <PublishSingleFile>true</PublishSingleFile>
    <IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>
    <PlatformTarget>x64</PlatformTarget>
  </PropertyGroup>

</Project>

我将运行时标识符设置为winx64并将单个文件设置为 true,但是在构建时,我留下了一堆我的应用程序使用的 DLL(总共 272 个)。我想知道 - 我如何将这些 DLL 打包到这个应用程序中?我曾认为将其发布为单个文件可执行文件已经可以做到这一点。

EXE旁边的DLL图片

标签: .net-coreroslyn.net-core-publishsinglefileasp.net-core-5.0

解决方案


对于 .NET 5,要在发布项目时获取单个可运行的可执行文件,重要的属性是:

  • 发布单个文件
  • 自给自足
  • IncludeAllContentForSelfExtract
  • 运行时标识符

您要么需要将它们本身包含在项目文件中,要么在命令行中指定它们。

项目文件:

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <!--<OutputType>WinExe</OutputType>--><!--Use this for WPF or Windows Forms apps-->
        <TargetFramework>net5.0</TargetFramework>
        <!--<TargetFramework>net5.0-windows</TargetFramework>--><!--Use this for WPF or Windows Forms apps-->
        <PublishSingleFile>true</PublishSingleFile>
        <SelfContained>true</SelfContained>
        <IncludeAllContentForSelfExtract>true</IncludeAllContentForSelfExtract>
        <RuntimeIdentifier>win-x64</RuntimeIdentifier><!--Specify the appropriate runtime here-->
    </PropertyGroup>

</Project>

命令行:

dotnet publish -r win-x64 --self-contained true -p:PublishSingleFile=true -p:IncludeAllContentForSelfExtract=true

根据您的需求,还有其他值得考虑的属性,例如:

  • 发布修剪
  • PublishReadyToRun

请参阅此处的文档页面:

https://docs.microsoft.com/en-us/dotnet/core/deploying/single-file https://github.com/dotnet/designs/blob/main/accepted/2020/single-file/design.md


推荐阅读