Building and distributing programs
suggest changeWriting the program is half the job. The other half is turning it into something other people can run on their machines, ideally without having to install anything first.
The .NET SDK gives you several ways to do this, all through dotnet publish:
- framework-dependent: small output, but the user needs the .NET runtime installed
- self-contained: the runtime ships with your app, so nothing has to be installed
- single-file: the whole app is bundled into one executable
- trimmed: unused framework code is removed to cut the size
- Native AOT: compiled ahead of time to machine code, giving a small, fast-starting native binary
- .NET tool: packaged as a NuGet package and installed with
dotnet tool install
This article covers each one, measures the results, and shows how to stamp versions and build release binaries in CI. It assumes the .NET 10 SDK.
build, run and publish
Start with a small program that reports where and how it runs:
using System.Reflection;
using System.Runtime.InteropServices;
var asm = Assembly.GetEntryAssembly()!;
string version = asm.GetCustomAttribute<AssemblyInformationalVersionAttribute>()
?.InformationalVersion ?? "unknown";
Console.WriteLine($"hello {version}");
Console.WriteLine($"Runtime: {RuntimeInformation.FrameworkDescription}");
Console.WriteLine($"OS/arch: {RuntimeInformation.RuntimeIdentifier}");
Console.WriteLine($"Exe path: {Environment.ProcessPath}");
Console.WriteLine($"Dynamic code: {System.Runtime.CompilerServices.RuntimeFeature.IsDynamicCodeSupported}");
The three commands you'll use most:
| Command | What it does | Default configuration | Output |
|---|---|---|---|
dotnet build |
compiles the project | Debug | bin/Debug/net10.0/ |
dotnet run |
builds if needed, then runs | Debug | same as build |
dotnet publish |
builds and gathers everything needed to deploy | Release | bin/Release/net10.0/publish/ |
Since .NET 8, dotnet publish uses the Release configuration by default, so you don't need -c Release (it does no harm to pass it anyway).
The output of dotnet build is meant for development, not for shipping:
$ dotnet build
$ ls bin/Debug/net10.0
hello.deps.json
hello.dll
hello.exe
hello.pdb
hello.runtimeconfig.json
hello.dllholds your compiled code as IL (intermediate language)hello.exeis a small native launcher (the apphost) that finds the runtime and loadshello.dll. On Linux and macOS it has no extensionhello.runtimeconfig.jsonsays which runtime version to loadhello.deps.jsonlists dependencies (NuGet packages and their files)hello.pdbholds debug symbols, used for file names and line numbers in stack traces
Use -o to publish to a directory of your choice:
$ dotnet publish -o out/fdd
hello -> ...\hello\out\fdd\
Framework-dependent deployment
The default publish is framework-dependent: the output holds only your code and its NuGet dependencies, and the program runs on the shared .NET runtime installed on the machine.
$ ls -l out/fdd
409 hello.deps.json
5632 hello.dll
162304 hello.exe
11056 hello.pdb
342 hello.runtimeconfig.json
That's under 200 KB. The runtimeconfig.json says which runtime is needed:
{
"runtimeOptions": {
"tfm": "net10.0",
"framework": {
"name": "Microsoft.NETCore.App",
"version": "10.0.0"
}
}
}
By default the app runs on the newest installed patch of the requested major version (10.0.x), so security fixes to the runtime apply without rebuilding. It won't run on .NET 11 unless you set <RollForward>Major</RollForward> in the project file.
Framework-dependent publishing is a good fit when:
- you control the machines (servers, containers built from the
mcr.microsoft.com/dotnet/runtimeimage, internal tools) - several apps share one runtime and you want each to stay small
If the runtime is missing, the apphost prints an error with a download link. That's a poor first experience for end users, which is why desktop and CLI apps are usually published self-contained.
Runtime identifiers
To ship a runtime with your app, the SDK has to know which OS and CPU to target. This is the runtime identifier (RID), passed with -r:
| RID | Platform |
|---|---|
win-x64 |
Windows, 64-bit Intel/AMD |
win-arm64 |
Windows on ARM |
linux-x64 |
Linux with glibc (Ubuntu, Debian, Fedora, ...) |
linux-musl-x64 |
Linux with musl (Alpine) |
linux-arm64 |
Linux on ARM64 (Raspberry Pi 4/5, AWS Graviton) |
osx-arm64 |
macOS on Apple Silicon |
osx-x64 |
macOS on Intel |
You can see the RID of the machine you're on in the program's output (OS/arch: win-x64), which comes from RuntimeInformation.RuntimeIdentifier.
Passing a RID on its own still gives a framework-dependent app, but with a platform-specific apphost and native dependencies for that platform only.
Self-contained deployment
Add --self-contained and the whole .NET runtime is copied into the output:
$ dotnet publish -r linux-x64 --self-contained -o out/sc-linux
$ ls out/sc-linux | wc -l
192
$ du -sh out/sc-linux
80M out/sc-linux
The user can now unzip the folder and run ./hello on any x64 Linux system, with no .NET installed. The cost is size, and the fact that runtime security updates now reach your users only when you ship a new build.
Cross-compiling works for self-contained apps: the command above ran on Windows and produced Linux binaries. The SDK downloads the runtime pack for the target RID from NuGet.
Single-file executables
192 files is awkward to distribute. PublishSingleFile bundles everything into one executable:
$ dotnet publish -r win-x64 --self-contained -p:PublishSingleFile=true -o out/single
$ ls -l out/single
73524921 hello.exe
11068 hello.pdb
At startup the bundle is memory-mapped and managed assemblies are loaded straight from it, without extracting to disk. Native libraries that a NuGet package carries are the exception: they stay as separate files next to the exe, unless you set IncludeNativeLibrariesForSelfExtract, in which case they're extracted to a temp directory on first run.
You can trade some startup time for size by compressing the bundle:
$ dotnet publish -r win-x64 --self-contained -p:PublishSingleFile=true \
-p:EnableCompressionInSingleFile=true -o out/comp
$ ls -l out/comp/hello.exe
37587066 hello.exe
Single-file also works framework-dependent, which gives a single small exe that still needs the runtime installed:
$ dotnet publish -r win-x64 --self-contained false -p:PublishSingleFile=true -o out/single-fdd
$ ls -l out/single-fdd/hello.exe
169956 hello.exe
Things to watch for in single-file apps:
Assembly.Locationreturns an empty string, because assemblies don't come from files. UseAppContext.BaseDirectoryto find the directory the exe is in, andEnvironment.ProcessPathfor the exe itself- the build emits warning
IL3000if your code (or a library) usesAssembly.Location - the
.pdbis a separate file. Set<DebugType>embedded</DebugType>to put the symbols inside the exe so stack traces still have line numbers
Trimming
A self-contained app carries the entire base class library, even though a hello-world uses a tiny fraction of it. Trimming (the ILLink tool) analyzes your app, starting from Main, and removes the types and methods that can't be reached:
$ dotnet publish -r win-x64 --self-contained -p:PublishSingleFile=true \
-p:PublishTrimmed=true -o out/trim
$ ls -l out/trim/hello.exe
12936910 hello.exe
That's 12.9 MB instead of 73.5 MB.
Trimming has to know at compile time what code is used. Reflection that looks up types or members by a string computed at run time defeats that:
string typeName = args.Length > 0 ? args[0] : "System.Text.StringBuilder";
Type? t = Type.GetType(typeName);
object? o = t is null ? null : Activator.CreateInstance(t);
Console.WriteLine(o?.GetType().FullName ?? "not found");
The trimmer warns about it:
$ dotnet publish -r win-x64 -p:PublishTrimmed=true -o out
Program.cs(2,11): warning IL2057: Unrecognized value passed to the parameter 'typeName'
of method 'System.Type.GetType(String)'. It's not possible to guarantee the availability
of the target type.
And the warning is real. The type exists when running normally, but has been trimmed away in the published app:
$ dotnet run -- System.Collections.ArrayList
System.Collections.ArrayList
$ ./out/plug.exe System.Collections.ArrayList
not found
Take trim warnings seriously: a trimmed app with warnings might fail at run time in ways your tests won't catch. The fix is to make the code statically analyzable, for example by replacing the string lookup with an explicit table:
var factories = new Dictionary<string, Func<object>>
{
["list"] = () => new System.Collections.ArrayList(),
["map"] = () => new System.Collections.Hashtable(),
};
string name = args.Length > 0 ? args[0] : "list";
object? o = factories.TryGetValue(name, out var make) ? make() : null;
Console.WriteLine(o?.GetType().FullName ?? "not found");
$ dotnet publish -r win-x64 -p:PublishTrimmed=true -o out
$ ./out/plug.exe list
System.Collections.ArrayList
$ ./out/plug.exe map
System.Collections.Hashtable
No warnings, and both types survive. For code that genuinely needs reflection, annotate it with [DynamicallyAccessedMembers] or [DynamicDependency] so the trimmer knows what to keep. Libraries that are safe to trim say so with <IsTrimmable>true</IsTrimmable>. Older libraries, and anything built on runtime reflection like classic Newtonsoft.Json or many dependency-injection and ORM libraries, may not be. JSON serialization with System.Text.Json is trim-safe when you use its source generator (JsonSerializerContext).
ReadyToRun: faster startup
Normally IL is compiled to machine code by the JIT as methods are first called. ReadyToRun (R2R) precompiles the IL to native code at publish time, and the JIT can still recompile hot methods later. That cuts startup time at the cost of larger files:
$ dotnet publish -r win-x64 --self-contained false -p:PublishReadyToRun=true -o out/r2r
$ ls -l out/r2r/hello.dll
20480 hello.dll
The DLL went from 5.6 KB to 20 KB. R2R requires a RID.
The framework itself ships precompiled with R2R. Trimming rewrites the framework assemblies, and the rewritten assemblies lose that precompiled code, so a trimmed app JIT-compiles everything at startup. Here are startup times averaged over 20 runs of the program above:
| Publish mode | Size | Startup |
|---|---|---|
| framework-dependent | 0.2 MB (+ runtime) | 103 ms |
| self-contained single-file | 73.5 MB | 80 ms |
| single-file, compressed | 37.6 MB | 154 ms |
| single-file, trimmed | 12.9 MB | 303 ms |
| single-file, trimmed + ReadyToRun | 16.9 MB | 68 ms |
| Native AOT | 1.8 MB | 24 ms |
These numbers were measured on Windows x64 with .NET 10.0.12. Your numbers will differ, but the pattern holds: if you trim, also enable ReadyToRun.
Native AOT
Native AOT compiles the app and the parts of the runtime it uses into a single native executable. There's no JIT and no IL at run time:
$ dotnet publish -r win-x64 -p:PublishAot=true -o out/aot
$ ls -l out/aot
1843200 hello.exe
9424896 hello.pdb
$ ./out/aot/hello.exe
hello 1.0.0
Runtime: .NET 10.0.12
OS/arch: win-x64
Exe path: C:\...\hello\out\aot\hello.exe
Dynamic code: False
A 1.8 MB executable that starts in about 24 ms. RuntimeFeature.IsDynamicCodeSupported returns False because there's no JIT to compile new code.
You can shrink it further with a few options:
$ dotnet publish -r win-x64 -p:PublishAot=true -p:InvariantGlobalization=true \
-p:OptimizationPreference=Size -p:StackTraceSupport=false -o out/aot2
$ ls -l out/aot2/hello.exe
1354752 hello.exe
InvariantGlobalizationdrops culture-specific data (ICU). Culture-sensitive formatting and comparison then behave like the invariant cultureOptimizationPreference=Sizefavors smaller code over faster codeStackTraceSupport=falseremoves method names from stack traces, which makes crashes much harder to diagnose. Usually not worth it
Native AOT has real restrictions:
- everything trimming requires applies, plus warnings for dynamic code (
IL3050): noReflection.Emit, no compiling expression trees to IL, andMakeGenericTypeonly works when the compiler can see the instantiation - no loading of assemblies at run time (
Assembly.LoadFrom), so no plugin systems based on that - no cross-OS compilation. You need the platform's native toolchain: on Windows, Visual Studio with the "Desktop development with C++" workload; on Linux,
clangand the zlib development package; on macOS, Xcode command-line tools. Trying to buildlinux-x64on Windows fails:
$ dotnet publish -r linux-x64 -p:PublishAot=true
error : Cross-OS native compilation is not supported.
Compiling for a different CPU on the same OS (for example win-arm64 on an x64 Windows machine) does work if the toolchain for that CPU is installed.
Native AOT is a great fit for command-line tools, small services and serverless functions, where startup time and size matter. Libraries such as System.Text.Json (with source generation), the minimal API subset of ASP.NET Core and System.CommandLine support it.
Putting publish settings in the project file
Long command lines are easy to get wrong. Put the settings in the .csproj and dotnet publish alone does the right thing:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Version>2.1.0</Version>
</PropertyGroup>
<!-- Deployment settings -->
<PropertyGroup>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<SelfContained>true</SelfContained>
<PublishSingleFile>true</PublishSingleFile>
<PublishTrimmed>true</PublishTrimmed>
<PublishReadyToRun>true</PublishReadyToRun>
<InvariantGlobalization>true</InvariantGlobalization>
<DebugType>embedded</DebugType>
</PropertyGroup>
</Project>
$ dotnet publish
hello -> ...\bin\Release\net10.0\win-x64\publish\
$ ls -l bin/Release/net10.0/win-x64/publish
16554956 hello.exe
$ ./bin/Release/net10.0/win-x64/publish/hello.exe
hello 2.1.0
...
Because <DebugType>embedded</DebugType> is set, there's no separate .pdb, just one file to ship.
The Publish* properties only affect dotnet publish. RuntimeIdentifier, SelfContained and InvariantGlobalization also apply to dotnet build and dotnet run. If you target several platforms, leave RuntimeIdentifier out of the project and pass -r on the command line, as in the CI example below.
Stamping the version
Users and bug reports need to know exactly which build is running. The SDK generates assembly attributes from MSBuild properties, so you don't need an AssemblyInfo.cs file:
| Property | Sets |
|---|---|
Version |
the default for all the ones below, e.g. 1.4.2 |
AssemblyVersion |
the version the runtime uses for binding |
FileVersion |
the Windows file version shown in Explorer |
InformationalVersion |
free-form "product version", read by the program above |
Set the version from the command line at release time:
$ dotnet publish -o out/ver -p:Version=1.4.2 -p:SourceRevisionId=3f9c2ab
$ ./out/ver/hello.exe
hello 1.4.2+3f9c2ab
...
The SDK appends SourceRevisionId to the informational version after a +. When building inside a git repository it does this automatically with the current commit hash, so a build from a clean checkout reports something like 1.4.2+3f9c2ab51e.... Turn that off with <IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>.
A --version flag is then just:
if (args is ["--version"])
{
string v = typeof(Program).Assembly
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "?";
Console.WriteLine(v);
return 0;
}
See Command-line arguments for proper argument parsing.
File-based apps
Since .NET 10 you can run a single .cs file without a project file. Dependencies and settings go in #: directives at the top:
#:package Humanizer@2.14.1
using Humanizer;
var started = DateTime.UtcNow.AddMinutes(-90);
Console.WriteLine($"Started {started.Humanize()}");
Console.WriteLine($"{"building_and_distributing".Humanize(LetterCasing.Title)}");
$ dotnet run app.cs
Started an hour ago
Building and Distributing
dotnet publish app.cs turns it into a distributable binary, and for file-based apps Native AOT is on by default:
$ dotnet publish app.cs
Humanizer.dll : warning IL3053: Assembly 'Humanizer' produced AOT analysis warnings.
Humanizer.dll : warning IL2104: Assembly 'Humanizer' produced trim warnings.
app.cs -> ...\artifacts\app\
$ ls -l artifacts/app
4317184 app.exe
17821696 app.pdb
$ ./artifacts/app/app.exe
Started an hour ago
Building and Distributing
The warnings come from Humanizer, an older library that isn't annotated for trimming. This particular program happens to work, but you'd need to test it properly before shipping. Add #:property PublishAot=false to the file to get a regular framework-dependent publish instead.
When a script outgrows a single file, dotnet project convert app.cs generates a normal .csproj from it.
Distributing as a .NET tool
If your users are .NET developers, the easiest way to ship a command-line tool is as a .NET tool: a NuGet package that dotnet tool install puts on the PATH. Add a few properties to the project:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<PackAsTool>true</PackAsTool>
<ToolCommandName>wordcount</ToolCommandName>
<PackageId>Example.WordCount</PackageId>
<Version>1.0.0</Version>
<Authors>Jane Doe</Authors>
<Description>Counts words in files.</Description>
<PackageOutputPath>./nupkg</PackageOutputPath>
</PropertyGroup>
</Project>
with a simple Program.cs:
if (args.Length == 0)
{
Console.Error.WriteLine("usage: wordcount <file>...");
return 1;
}
foreach (string path in args)
{
string text = File.ReadAllText(path);
int words = text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries).Length;
Console.WriteLine($"{words,8} {path}");
}
return 0;
Pack it, install it from the local folder, and run it:
$ dotnet pack
Successfully created package '...\nupkg\Example.WordCount.1.0.0.nupkg'.
$ dotnet tool install --tool-path ./tools --add-source ./nupkg Example.WordCount
You can invoke the tool using the following command: wordcount
Tool 'example.wordcount' (version '1.0.0') was successfully installed.
$ ./tools/wordcount t.txt Program.cs
4 t.txt
31 Program.cs
Once the package is pushed to nuget.org (dotnet nuget push, see NuGet), users install it globally with dotnet tool install -g Example.WordCount, or run it once without installing:
$ dotnet tool exec Example.WordCount -- t.txt
4 t.txt
.NET 10 also ships dnx as a shorthand for dotnet tool exec, similar to npx for Node.js.
A tool is framework-dependent and needs a compatible .NET runtime on the user's machine. Use it for developer audiences. For everyone else, ship a self-contained or Native AOT binary.
Building release binaries in CI
Native AOT can't cross-compile between operating systems, and it's good practice to build each platform's binary on that platform anyway. A GitHub Actions matrix builds all of them in parallel:
name: release
on:
push:
tags: ["v*"]
jobs:
publish:
strategy:
matrix:
include:
- os: windows-latest
rid: win-x64
- os: ubuntu-latest
rid: linux-x64
- os: macos-latest
rid: osx-arm64
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v5
- uses: actions/setup-dotnet@v5
with:
dotnet-version: "10.0.x"
- name: Publish
shell: bash
run: |
VERSION="${GITHUB_REF_NAME#v}"
dotnet publish src/hello/hello.csproj -r ${{ matrix.rid }} \
-p:PublishAot=true -p:Version=$VERSION -o dist/${{ matrix.rid }}
- uses: actions/upload-artifact@v5
with:
name: hello-${{ matrix.rid }}
path: dist/${{ matrix.rid }}
Pushing a tag such as v1.4.2 builds three native binaries, each reporting version 1.4.2+<commit>. The GitHub-hosted Windows, Ubuntu and macOS runners already have the C++ toolchains Native AOT needs. To run your tests in the same pipeline, see Testing in CI.
Containers
For server apps, the SDK can build an OCI container image directly, without a Dockerfile:
$ dotnet publish -r linux-x64 -t:PublishContainer -p:ContainerRepository=hello
This builds the image on top of the matching mcr.microsoft.com/dotnet/runtime (or aspnet, runtime-deps for self-contained) base image and loads it into the local Docker or Podman daemon. Set ContainerRegistry to push it to a registry instead. The same publish options apply: a trimmed or Native AOT app gets a much smaller image.
Choosing a deployment mode
- Server or container you control: framework-dependent, or a container image built with
PublishContainer - Tool for .NET developers:
PackAsTooland publish to NuGet - CLI tool or small utility for anyone: Native AOT if your code and dependencies are AOT-compatible; otherwise self-contained single-file, trimmed, with ReadyToRun
- Desktop app (WinForms/WPF): self-contained single-file. WinForms and WPF don't support trimming or Native AOT, because they rely heavily on reflection
- Quick script: a file-based app with
dotnet run app.cs
Whatever mode you choose, test the published output, not just dotnet run. Trimming, AOT and single-file all change runtime behavior, and the differences only show up in the published binary.