Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the current executing directory on linux with .Net Core?

I need to load in an XML schema file to validate some information on a .Net Core 2.1 api that is on a linux server. Unfortunately, I do not have access to this server (we use jenkins to deploy so I have 0 contact with it), so I can only test on my computer which is Windows 10.
I have tried the following:

System.AppContext.BaseDirectory
System.AppContext.BaseDirectory.Substring(0, AppContext.BaseDirectory.IndexOf("bin"));
AppDomain.CurrentDomain.BaseDirectory
Directory.GetCurrentDirectory()
GetType().Assembly.Location
System.Reflection.Assembly.GetExecutingAssembly().Location
System.Reflection.Assembly.GetExecutingAssembly().CodeBase

All of these return the current execution location on Windows (i.e. C:/SomePath/SomeProject/Name/api.dll) which I can use with Path.Combine to produce the path to the schema file.

However, on linux, these all return /home/app/ which is not where the dll should be according to the Jenkins logs. This is leading to failures loading the schema file. The project is actually located under /services/projectname/.

Test Code:

var schema = new XmlSchemaSet { XmlResolver = new XmlUrlResolver() };
schema.Add(null, Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Schema/schema.xsd"));

Expected: On Windows and Linux this loads the schema file using the .dll execution path as the base.

Actual: On Linux I get home/app instead of the correct path.

Edit: I cannot hardcode the path. The path changes on every deployment as the project name is versioned. This means the second I deploy it, any hardcoded value will be incorrect. I absolutely require a relative path. Beyond that technical requirement, hard coding is a major taboo. I will never get it past a code review.

like image 791
Susannah Potts Avatar asked Dec 02 '25 05:12

Susannah Potts


1 Answers

For me, in dotnet core 3.1 the following statement works for a console application in both Windows and Ubuntu:

Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
like image 175
Mark Avatar answered Dec 03 '25 17:12

Mark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!