23

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?

Erik Dekker
  • 2,395
  • 5
  • 33
  • 55

7 Answers7

36
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.

Aaron McIver
  • 24,527
  • 5
  • 59
  • 88
  • On second thought is your answer better, since you give me the directory, and thats what i asked for. Rest gives me paths to the assembly file. – Erik Dekker Nov 30 '11 at 13:46
  • @Erik: Do you need directory name only or full path? – abatishchev Nov 30 '11 at 14:33
  • @abatishchev: Well the last line in my question was: "how I can get the application directory", I need the full path to the application directory. Your answer is good, but it did not give me the directory, it gave me the assembly file. – Erik Dekker Nov 30 '11 at 15:42
6

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.

dsolimano
  • 8,870
  • 3
  • 48
  • 63
5

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.

Ratan
  • 863
  • 5
  • 12
  • 28
3
Assembly.GetExecutingAssembly().Location

See also GetCallingAssembly() and GetEntryAssembly().

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

Community
  • 1
  • 1
abatishchev
  • 98,240
  • 88
  • 296
  • 433
1

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

NoNaMe
  • 6,020
  • 30
  • 82
  • 110
Owen
  • 17
  • 1
1

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

Also see Best way to get application folder path
Alexander
  • 540
  • 6
  • 12
1

Can you try what this returns ?

System.IO.Path.GetDirectoryName(Application.ExecutablePath) 
Shyju
  • 214,206
  • 104
  • 411
  • 497