Windows Task Scheduler – Environment.CurrentDirectory Issue – Simple Tip

Sathish Nadarajan
 
Solution Architect
February 13, 2019
 
Rate this article
 
Views
2986

I was writing a Console Application which targets against a SharePoint Online tenant which will do some sort of regular activity. Hence, we configured the Console Application on the Task Scheduler. (Though, there are lot other options, for our scenario, we went ahead with the Task Scheduler ). The Console Application uses a Configuration File, which I kept on the bin/debug folder during the development and from the Code, I consumed with Environment.CurrentDirectory property and it was working fine. But, when I configure the same EXE on the Task Scheduler, it was not working. Because, the reason is, the Task Scheduler triggers the EXE from the location C:\Windows\System32 folder. Either we need to paste the Config.XML file on the System32 folder or we need to change our code. The change is very simple. Instead of using the “Environment.Currentdirectory”, we can use the below code snippet.

Old Code Snippet

 var configFile = Path.Combine(Environment.CurrentDirectory, "Config.xml");
             System.Console.WriteLine(configFile);
             System.Console.WriteLine("Completed");
             System.Console.ReadLine();
 

Updated Code Snippet

 namespace Office365.Console
 {
     using System;
     using System.Collections.Concurrent;
     using System.IO;
     using System.Reflection;
 
     class Program
     {
         private static ConcurrentDictionary<Uri, RESTFormDigest> FormDigests { get; set; }
 
         static void Main(string[] args)
         {
             var configFile = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Config.xml");
             System.Console.WriteLine(configFile);
             System.Console.WriteLine("Completed");
             System.Console.ReadLine();
         }
     }
 } 
 

We need to use the System.Reflection namespace and the method “Assembly.GetExecutingAssembly()”. Thought it is very simple, it took few mins for me to identify on the production environment.

Happy Coding,

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment