L
L
Lizard2021-09-05 22:48:54
.NET
Lizard, 2021-09-05 22:48:54

How to compile a C# project into one .exe file?

Hello.
I wrote a simple C# console application for Windows.
There is a task to compile a small project into 1 .exe file. That is, hide the .dll files that are created after compilation.
Most of the "google" does not work (articles from 2001-2012). I think the issue is relevant.
What means do you use?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vasily Bannikov, 2021-09-05
@rootovich1

Single File Application - a feature of modern dotnets since .net Core 3
Literally, with the help of one option in the project file or one line in the console, it assembles your project into a single executable, which can also optionally have a built-in runtime.
Here is an example csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <PropertyGroup>
    <!-- Вот это самое главное -->
    <PublishSingleFile>true</PublishSingleFile>
    <!-- Это чтобы тащить за собой рантайм До .NET 6 будут рядом лежать нативные библиотеки jit-а и сборщика мусора-->
    <SelfContained>true</SelfContained>
    <!-- Это необходимо, чтобы сборщик понимал, для какой ОС нужен экзешник -->
    <RuntimeIdentifier>win-x64</RuntimeIdentifier>
    <!-- Это чтобы ускорить запуск -->
    <PublishReadyToRun>true</PublishReadyToRun>
    <!-- Эти две строки, чтобы уменьшить размер бинарника -->
    <PublishTrimmed>true</PublishTrimmed>
    <TrimMode>link</TrimMode>
  </PropertyGroup>
</Project>

The result is the only exe that can really be run anywhere, regardless of the version of .NET installed.
For older versions of dotnet, there is ILMerge and Costura.Fody , but in .net 5 they are not needed, and I highly recommend using .NET 5 ( and soon 6 more will be released)

D
Developer, 2021-09-05
@samodum

Do not use References, move everything to the main project

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question