I have a console app which is located on my desktop. I have set it to a Scheduled Task to run every 20 Minutes indefinitely. I have turned off auto sleep/hibernate. Then I left my PC ON and locked my desktop for the weekend (2-3 days).
My console app was developed to email me every time it catches an exception. When I returned, checked my inbox received a couple of error emails containing
Access to the path 'C:\WINDOWS\system32\myLogs\' is denied.
it seemed my console app was being run from System32 not from my Desktop.
Q: Why is it behaving like it?
this is my string on creating my myLog folder path
var logpath = Directory.GetCurrentDirectory() + Properties.Settings.Default.LogPath;
this checks if the folder exists, if not it creates a new folder.
if (!Directory.Exists(logpath))
Directory.CreateDirectory(logpath);
I believe the error was triggered on checking/creating the folder.
My app should create the myLog folder in the same directory as my console app.
Q: Why is it running from System32 Folder?
Scheduled Tasks are launched by the Task Scheduler service. This service runs inside the C:\Windows\System32\svchost.exe executable. By default, all applications launched by the Task Scheduler are launched with C:\Windows\System32 as the current directory.
You can change the start directory in the Edit Action dialog of the Task Scheduler:

You can use environment variables. For example, %USERPROFILE% will set the start directory to the user's profile directory (eg. C:\Users\MyUsername).
Rather than changing the start directory for the scheduled task, you may want to find the the directory where the console application executable is located:
System.Reflection.Assembly.GetExecutingAssembly().Location
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With