發佈 .NET 5 帶運行時單文件應用時優化文件體積的方法

  • 2021 年 5 月 15 日
  • 筆記

自 .NET 發佈起,.NET Framework 運行環境就是其擺脫不掉的桎梏。後來有了 .NET Core ,微軟終於將自帶運行時和單文件程序帶給了我們。即便如此,大部分情況下開發者仍然不太滿意:一個簡簡單單的控制台應用程序,甚至只包含一個 Hello World ,附帶運行時的單文件程序打包出來就需要 20M+ 。

.NET 程序的發佈受一個名為 發佈配置文件 (.pubxml) 的 XML 文件控制,該文件默認不存在,會在第一次在 Visual Studio 中執行發佈時創建。該文件會被保存在項目的 Properties/PublishProfiles 目錄下,可以在以下微軟文檔上看到更詳細的介紹: 

//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"?>
<!--
//go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project ToolsVersion="4.0" xmlns="//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"?>
<!--
//go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project ToolsVersion="4.0" xmlns="//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>

詳細的裁剪選項可以參看微軟的官方文檔:

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