本文由 发布,转载请注明出处,如有问题请联系我们! 发布时间: 2021-05-16发布 .NET 5 带运行时单文件应用时优化文件体积的方法

加载中

发布 .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条)

刀客源码 游客评论