Original assembly location in .NET 5.0 Linux with Single-File Executable

Issue

I’ve found numerous answers relating to .NET Core 3.1 and .NET 5.0 on Windows, but so far have been unable to find how to get the original assembly location under .NET Core on Linux when using a single-file executable. Given that the systems behave differently, I think this is probably a bug in .NET 5, but I need a workaround in the mean time. Note that in my scenario, the current directory is not where the original executable is located, even if I don’t change it, and I have no control over it (and that’s a hack anyway–the purpose of current directory is completely different). Here’s the actual output of a test program under this scenario with the properties and functions that have been suggested in all the other posts I’ve been able to find so far:

Directory.CurrentDirectory()=/home/ec2-user/source
typeof(Program).Assembly.Location=/root/.net/Test/jwaxs3pc.bdp/Test.dll
typeof(Program).Assembly.GetFiles() [0].Name=/root/.net/Test/jwaxs3pc.bdp/Test.dll
typeof(Program).Assembly.GetName().CodeBase=file:///root/.net/Test/jwaxs3pc.bdp/Test.dll
AppContext.BaseDirectory=/root/.net/Test/jwaxs3pc.bdp/
Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName=/root/.net/Test/jwaxs3pc.bdp

I need to find the original code location, not the location the single-file executable was decompressed into. How do I get this most basic of all information? Is there not a platform and setting-independent way to do this (there really should be)?

Solution

When you publish your app as single executable file, some APIs related to Assembly will not work, and this is not a bug.

It is documented here:
https://docs.microsoft.com/en-us/dotnet/core/deploying/single-file#api-incompatibility

There you’ll see in that table that Assembly.Location will always return empty string when running in a single executable file.
As suggested in that doc, you could call Environment.GetCommandLineArgs() and evaluate the value of the first item in the string array result.

Answered By – Eriawan Kusumawardhono

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published