Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get application folder when program is started by Windows Task Scheduler

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?

like image 375
Erik Dekker Avatar asked Nov 29 '11 15:11

Erik Dekker


People also ask

Where do Scheduled Tasks get stored?

Yes, I know that the scheduled tasks are stored in the registry (HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule...) and the mentioned folder with the task is visible there.

Can I trigger a scheduled task when the contents of a folder change?

Scheduled tasks cannot be triggered based upon file system changes. The event-based trigger that is supported is really for listening to events in the event log.


4 Answers

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.

like image 55
Aaron McIver Avatar answered Sep 18 '22 14:09

Aaron McIver


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.

like image 25
dsolimano Avatar answered Sep 19 '22 14:09

dsolimano


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.

like image 45
Ratan Avatar answered Sep 20 '22 14:09

Ratan


Assembly.GetExecutingAssembly().Location

See also GetCallingAssembly() and GetEntryAssembly().

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

like image 32
abatishchev Avatar answered Sep 20 '22 14:09

abatishchev