发布 .NET 5 带运行时单文件应用时优化文件体积的方法

自 .NET 发布起,.NET Framework 运行环境就是其摆脱不掉的桎梏。后来有了 .NET Core ,微软终于将自带运行时和单文件程序带给了我们。即便如此,大部分情况下开发者仍然不太满意:一个简简单单的控制台应用程序,甚至只包含一个 Hello World ,附带运行时的单文件程序打包出来就需要 20M+ 。

.NET 程序的发布受一个名为 发布配置文件 (.pubxml) 的 XML 文件控制,该文件默认不存在,会在第一次在 Visual Studio 中执行发布时创建。该文件会被保存在项目的 Properties/PublishProfiles 目录下,可以在以下微软文档上看到更详细的介绍:

https://docs.microsoft.com/zh-cn/aspnet/core/host-and-deploy/visual-studio-publish-profiles?view=aspnetcore-5.0

通过阅读文档和不断尝试,笔者得出了一个可以优化打包文件的发布配置文件:

<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <Configuration>Release</Configuration>
    <Platform>Any CPU</Platform>
    <PublishDir>bin\Release\net5.0\publish\</PublishDir>
    <PublishProtocol>FileSystem</PublishProtocol>
    <TargetFramework>net5.0</TargetFramework>
    <RuntimeIdentifier>linux-arm</RuntimeIdentifier>
    <SelfContained>true</SelfContained>
    <PublishSingleFile>True</PublishSingleFile>
    <PublishTrimmed>True</PublishTrimmed>
    <TrimMode>link</TrimMode>
  </PropertyGroup>
</Project>

使用以上发布配置,最终发布文件体积从 20M 降低到了 8.7M ,使用 WinRar 压缩之后为 3.33 M 左右。

你也可以使用下面配置来进一步减小文件体积:

<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <Configuration>Release</Configuration>
    <Platform>Any CPU</Platform>
    <PublishDir>bin\Release\net5.0\publish\</PublishDir>
    <PublishProtocol>FileSystem</PublishProtocol>
    <TargetFramework>net5.0</TargetFramework>
    <RuntimeIdentifier>linux-arm</RuntimeIdentifier>
    <SelfContained>true</SelfContained>
    <PublishSingleFile>True</PublishSingleFile>
    <PublishTrimmed>True</PublishTrimmed>
    <TrimMode>link</TrimMode>
    <DebuggerSupport>false</DebuggerSupport>
    <EnableUnsafeBinaryFormatterSerialization>false</EnableUnsafeBinaryFormatterSerialization>
    <EnableUnsafeUTF7Encoding>false</EnableUnsafeUTF7Encoding>
    <EventSourceSupport>false</EventSourceSupport>
    <HttpActivityPropagationSupport>false</HttpActivityPropagationSupport>
    <InvariantGlobalization>true</InvariantGlobalization>
    <UseSystemResourceKeys>true</UseSystemResourceKeys>
    <TrimmerRemoveSymbols>true</TrimmerRemoveSymbols>
  </PropertyGroup>
</Project>

详细的裁剪选项可以参看微软的官方文档:

https://docs.microsoft.com/zh-cn/dotnet/core/deploying/trimming-options

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值