發布 .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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM