Petr
Petr

Reputation: 334

AppContext.BaseDirectory in C# PowerShell module returns unexpected path

I have a PowerShell module written in C#. I have a "Assets" directory with some files as part of the module. When I publish the module to a local directory, it has structure like this:

|- Assets
|- MyModule.deps.json
|- MyModule.dll
|- MyModule.pdb
|- MyModule.psd1
|- MyModule.psm1

The logic is implemented in MyModule.dll. It uses stuff in Assets directory. I get it's location using System.AppContext.BaseDirectory. The MyModule.dll is used also by other application (console app, win ui3), where everything works. In Powershell, it seems AppContext.BaseDirectory returns value of "$PSHOME" path, where my Assets directory does not exist.

Any ideas how to fix that? Why only for PowerShell the AppContext.BaseDirectory returns something else than where the dll actually is?

Upvotes: 0

Views: 217

Answers (1)

Sinus32
Sinus32

Reputation: 831

System.AppContext.BaseDirectory is the file path of the base directory that the assembly resolver uses to probe for assemblies. So in particular, it's not the file path of the base directory where the executing assembly resides. By coincidence it usually is the same, but don't have to be.

https://learn.microsoft.com/en-us/dotnet/api/system.appcontext.basedirectory?view=net-8.0

Try use something else, for e.g. Assembly.Location property.

Upvotes: 1

Related Questions