简体   繁体   中英

How to get the calling directory of a C# assembly?

I am trying to write a small build event utility to read the current assembly version of my code.

Thus, I want that executable to be in my %PATH% (or some central location at least) and be able to take a relative path to my target assembly as an argument (to Assembly.LoadFile() it) but Assembly.LoadFile() complains about receiving a relative path.

How can I do:

C:\calling\path>mytool rel\path\to\target.exe

Without having to type C:\devpath\to\mytool.exe every time?

And be able to get the string "C:\calling\path\rel\path\to\target.exe" in mytool.exe?

It turns out that this is a bit of a pain.

A C# assembly requires its support files to be in the same directory as itself so in the simple case, we can't just copy the exe to our chosen directory.

Another possibility is to create a shortcut to the exe and move that to the directory. Unfortunately, despite having an impressive amount of "current" path getters, C# doesn't have a way to know if it's been started through a shortcut.

When invoked from a shortcut in C:\calling\path, all of the following:

Console.WriteLine(Environment.CurrentDirectory);
Console.WriteLine(Directory.GetCurrentDirectory());
Console.WriteLine(Assembly.GetEntryAssembly().Location);
Console.WriteLine(System.AppDomain.CurrentDomain.BaseDirectory);
Console.WriteLine(System.AppContext.BaseDirectory);
//Console.WriteLine(Process.GetCurrentProcess().StartInfo.WorkingDirectory);
Console.WriteLine(Process.GetCurrentProcess().MainModule.FileName);
Console.WriteLine(Environment.GetCommandLineArgs()[0]);

return a variation of "C:\devpath\to". Except for Process.StartInfo which just crashes. You can't get the StartInfo of a process you didn't Process.Start(), including your own.

The only way that appears to work to be able to retrieve "C:\calling\path" is to create a batch file in "C:\inpath" that calls the original assembly directly.

So: C:\inpath\exe.bat:

C:\devpath\to\mytool.exe %*

C:\devpath\to\mytool.cs:

Console.WriteLine(Environment.CurrentDirectory);
Console.WriteLine(Directory.GetCurrentDirectory());

These 2 will return "C:\calling\path".

Another option could be to add C:\devpath\to itself to the PATH

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM