18
votes

I have a console app in c# thats starts on schuled times by the Windows task scheduler. The app needs some physical files from its own directory and uses System.IO.Directory.GetCurrentDirectory() for that.

Normal when I start the console app myself, it works perfectly. But when it is started by Windows Task Scheduler, it returns C:\Windows\System32.

Why is this not the application directory and is there another way how I can get the application directory?

7

7 Answers

31
votes
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

System.IO.Directory.GetCurrentDirectory() will return the current directory of the executing process which is not your application in this instance. The above will suffice in getting the execution directory your executable is running in.

5
votes

GetCurrentDirectory returns that directory because when the scheduler starts an application by default. If you want to know the directory that your binary is in, you can use

Assembly.GetExecutingAssembly().Location

I would also be curious to know if you have a "Start In" directory set in your scheduled task - setting that should also set the current directory of the application when it starts.

4
votes

Its an old thread, but for someone looking, while setting up the task, you can assign the location in the Action of the task, by setting the optional :Start in" value to your exe folder. GetCurrentDirectory will work fine then.

3
votes
Assembly.GetExecutingAssembly().Location

See also GetCallingAssembly() and GetEntryAssembly().

And What is the best way to determine application root directory?

1
votes

Can you try what this returns ?

System.IO.Path.GetDirectoryName(Application.ExecutablePath) 
0
votes

I use My.Application.Info.DirectoryPath is point to the correct directory what you want within Windows task scheduler.

0
votes

AppDomain.CurrentDomain.BaseDirectory Will get the directory if you want to use files relative to the install directory.

Best way to get application folder path