2

TL;DR

Why

System.Reflection.Assembly.GetExecutingAssembly().Location 

returns "<Unknown>"?

The whole story: When I run my console application manually, everything goes well. When I set Task Scheduler to run my app, there is a problem: my app can't find some dependent files. These files are written in the .config file like this: <add key="SomeFile" value="SomeFolder\SomeFile.xml"/>, I need only relative pathes.

When I run my app manually, 'current folder' = 'application folder', but when I run with Task Scheduler, 'current folder' = C:\Windows\system32, because with Task Scheduler my app runs under taskeng.exe which lies in system32.

So to find assembly path I want to use this code:

System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

from this answer https://stackoverflow.com/a/16102640/6184866.

But it doesn't work.

Community
  • 1
  • 1
Raman Sinclair
  • 1,194
  • 17
  • 31
  • you can get Directory.GetCurrentDirectory same it in some variable then Directory.SetCurrentDirectory to your required then again set current dir to temp once you are done with your work – Vivek Nuna Nov 08 '16 at 06:07

2 Answers2

1

After native compilation, the assembly no longer exists on the file system.

A more recent way to pull the current directory is:

AppContext.BaseDirectory

This works in .net6

HackSlash
  • 4,944
  • 2
  • 18
  • 44
0

I had this same issue also with a console application.

I only received this error when:

  1. The assembly is built as release with optimisations on
  2. The program is run outside of Visual Studio and then the process is attached to
  3. The command Assembly.GetExecutingAssembly().Location is executed via the Immediate Window.

It can be replicated with the following code. The sleep in a loop is just to give me time to attach the debugger.

static void Main(string[] args)
{
    for (int i = 0; i < 10; i++)
    {
        Console.WriteLine(10 - i);
        Thread.Sleep(1000);
    }

    Console.WriteLine(Assembly.GetExecutingAssembly().Location);
    Console.WriteLine(Directory.GetCurrentDirectory());

    Console.ReadLine();
}

Breakpointing this code (when the above constraints are true) and from the Immediate Window executing the command Assembly.GetExecutingAssembly().Location returns <Unknown>. Executing Directory.GetCurrentDirectory() returns Cannot evaluate expression because the code of the current method is optimized.

However, both commands execute and print the expected correct values to the console.

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Adam
  • 524
  • 8
  • 10