How can I reduce the size of a C # application that is environment independent?

In this article I will share my experience on how to reduce the size of an assembly-independent C # application by 2 - 4 times.





Attention: Compression of the program content is available only for self-contained publications . And also all actions take place in Visual Studio Preview 2019.





If you are here for a quick fix, here's what you need to do

In .csproject add the following lines:





Dangerous mode: removes unused classes and methods. Has a risk that the application will stop working correctly, therefore it requires testing all application functions after publication.





<PublishSingleFile>true</PublishSingleFile>
<SelfContained>true</SelfContained>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<PublishTrimmed>true</PublishTrimmed>
<TrimMode>Link</TrimMode>
      
      



Safer mode: only removes unused assemblies.





<PublishSingleFile>true</PublishSingleFile>
<SelfContained>true</SelfContained>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<PublishTrimmed>true</PublishTrimmed>
<TrimMode>CopyUsed</TrimMode>
      
      



Then right-click on the project → Publish → Folder → Finish → Show All Settings. Set the following settings:





  • Deployment Mode: Self-Contained





  • T arget Runtime: win-x64 or your version. (Must match the RuntimeIdentifier line )





Expand File publish options and check the boxes under: Produce single file and Trim unused assemblies .





Click the Publish button .






Everything is the same, only with a command

Dangerous Mode:





dotnet publish -c Release -r win10-x64 -p:PublishTrimmed=True -p:TrimMode=Link -p:PublishSingleFile=true --self-contained true
      
      



:





dotnet publish -c Release -r win10-x64 -p:PublishTrimmed=True -p:TrimMode=CopyUsed -p:PublishSingleFile=true --self-contained true
      
      




,

3 , Visual Studio.





PublishTrimmed .





TrimMode . .





2 : CopyUsed (Assembly-level trimming) Link (Member-Level Trimming).





Assembly-level trimming — . , , , . 300 96 . ZIP 30.





Member-Level Trimming — . , .. - , , , , . , 300 86, - . , .





You can read more about tests in this article.





Official documentation from Microsoft








All Articles