Executing assembly location in a Dotnet (core) single file app

How to get Assembly location for modern .NET projects embedded in a single-file app.

Executing Assembly location

To get executing assembly location you can invoke:

var executableDirectory = System.Reflection.Assembly.GetExecutingAssembly().Location;

But when you try to publish app as a single file, for example this way:

dotnet publish -c Release -r win-x64 --self-contained true -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true

then you will see following error:

error IL3000: 'System.Reflection.Assembly.Location' always returns an empty string for assemblies embedded in a single-file app. If the path to the app directory is needed, consider calling 'System.AppContext.BaseDirectory'

Current directory

You can achieve similar result with BaseDirectory property from AppContext class:

var executableDirectory = System.AppContext.BaseDirectory;

which will give you directory path of your single-file bundle.

Note that this is exactly what error message suggests, but I know that not everyone will read it to the end (maybe that’s why your here?) :)

Example usages

You can use this path for example to set current directory:

var executableDirectory = AppContext.BaseDirectory;
Directory.SetCurrentDirectory(executableDirectory ?? throw new Exception("Could not find out executable directory"));

Or to instruct configuration file provider without changing current directory:

var builder = WebApplication.CreateBuilder(args);

Pay attention to lines order - setting new base path after adding json file will cause searching for json file in old base path.


Retrieving application exe directory is still simple thing, but modern .NET is full of small changes which affects our lives, so I hope this short how-to will be helpful.

If in your version of .NET another approach is required, please share it with others in comment.



Passionate focused on agile software development and decentralized systems

Read More