Create File Watcher Window Service In C#

This article is useful when we need to monitor that the file is created or not after completion of job or any scheduled based task on server. I will create service for this kind of task which monitors the file which is created or not at a particular location.

Watch File creation at a specified location

If you are new in window service just go through below link.

Now we will see how to create service to watch folder.

Step 1: You need to add file path in App.config file.

Here I have added two file paths because I want to watch both the locations.

added two file paths

Code Snippet

  1. <appSettings>  
  2.    <add key="WatchPath1" value="D:\\articleimg" />  
  3.    <add key="WatchPath2" value="D:\\MYdata" />  
  4. </appSettings>  
Step 2: After that you need to drag and drop fileWatcher control from toolbox to service design section.
I have added two fileWatcher control for watch two locations of my computer.

service

Step 3: Now we need to write some code in Service.cs section.

Initially you need to access both the files from App.config file. Before writing the following code you need to add reference of System.Configuration in your window application.

System Configuration

Then add System.Configuration namespace in Service1.cs, after that you can write the following code.

configuration

Code Snippet
  1. string WatchPath1 = ConfigurationManager.AppSettings["WatchPath1"];  
  2. string WatchPath2 = ConfigurationManager.AppSettings["WatchPath2"];  
Step 4: After completing the preceding steps you need to allocate value to the fileWatcher on start of service like the following image.

allocate value to the filewatcher
Code Snippet
  1. protected override void OnStart(string[] args)  
  2. {  
  3.     try  
  4.     {  
  5.         fileWatcherWatchDdriveArticleimagefolder.Path = WatchPath1;  
  6.         fileWatcherWatchDDriveMYdataFolder.Path = WatchPath2;  
  7.     }  
  8.     catch (Exception ex)  
  9.     {  
  10.         throw ex;  
  11.     }  
  12. }  
Step 5: Now you need to work on fileWatcher created event. So I have fired an event in service.cs constructor. As I said I have used two fileWatcher, so I have fired event corresponding to each fileWatcher.

filewatcher

Step 6: Now I am going to describe code inside fileWatcher which I have written in fileWatcher created event. Here I will discuss only one file watcher code because I will use same piece of code in another fileWatcher event.

filewatcher event

Code Snippet
  1. /// <summary>  
  2. /// This event monitor folder wheater file created or not.  
  3. /// </summary>  
  4. /// <param name="sender"></param>  
  5. /// <param name="e"></param>  
  6. void fileWatcherWatchDDriveMYdataFolder_Created(object sender, System.IO.FileSystemEventArgs e)  
  7. {  
  8.     try  
  9.     {  
  10.         Thread.Sleep(70000);  
  11.         //Then we need to check file is exist or not which is created.  
  12.         if (CheckFileExistance(WatchPath2, e.Name))  
  13.         {  
  14.             //Then write code for log detail of file in text file.  
  15.             CreateTextFile(WatchPath2,e.Name);  
  16.         }  
  17.   
  18.     }  
  19.     catch (Exception ex)  
  20.     {  
  21.   
  22.         throw ex;  
  23.     }  
  24.   
  25. }  
Now I will show you CheckFileExistance method. In this method I have checked that directory and file exists or not and it returns true and false accordingly.

Code Snippet:
  1. private bool CheckFileExistance(string FullPath, string FileName)  
  2. {  
  3.     // Get the subdirectories for the specified directory.'  
  4.     bool IsFileExist = false;  
  5.     DirectoryInfo dir = new DirectoryInfo(FullPath);  
  6.     if (!dir.Exists)  
  7.         IsFileExist = false;  
  8.     else  
  9.     {  
  10.         string FileFullPath = Path.Combine(FullPath, FileName);  
  11.         if (File.Exists(FileFullPath))  
  12.             IsFileExist = true;  
  13.     }  
  14.     return IsFileExist;  
  15.   
  16.   
  17. }  
Now I will discuss about CreateTextFile method. This method called when above method returns true value. CreateTextFile method used to create text file for maintaining the status of file creation.

Code Snippet:
  1. private void CreateTextFile(string FullPath, string FileName)  
  2. {  
  3.     StreamWriter SW;  
  4.     if (!File.Exists(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "txtStatus_" + DateTime.Now.ToString("yyyyMMdd") + ".txt")))  
  5.     {  
  6.         SW = File.CreateText(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "txtStatus_" + DateTime.Now.ToString("yyyyMMdd") + ".txt"));  
  7.         SW.Close();  
  8.     }  
  9.     using (SW = File.AppendText(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "txtStatus_" + DateTime.Now.ToString("yyyyMMdd") + ".txt")))  
  10.     {  
  11.         SW.WriteLine("File Created with Name: " + FileName + " at this location: " + FullPath);  
  12.         SW.Close();  
  13.     }  
  14. }  
Step 7: Now I am writing a method which maintains the service stop status in text file. In this method I have created a text file and maintained service stop time.

Code Snippet:
  1. public static void Create_ServiceStoptextfile()  
  2. {  
  3.     string Destination = "D:\\articleimg\\FileWatcherWinService";  
  4.     StreamWriter SW;  
  5.     if (Directory.Exists(Destination))  
  6.     {  
  7.         Destination = System.IO.Path.Combine(Destination, "txtServiceStop_" + DateTime.Now.ToString("yyyyMMdd") + ".txt");  
  8.         if (!File.Exists(Destination))  
  9.         {  
  10.             SW = File.CreateText(Destination);  
  11.             SW.Close();  
  12.         }  
  13.     }  
  14.     using (SW = File.AppendText(Destination))  
  15.     {  
  16.         SW.Write("\r\n\n");  
  17.         SW.WriteLine("Service Stopped at: " + DateTime.Now.ToString("dd-MM-yyyy H:mm:ss"));  
  18.         SW.Close();  
  19.     }  
  20. }  
Then I will call above method on stop event of this service.

method

Code Snippet:
  1. protected override void OnStop()  
  2. {  
  3.    try  
  4.    {  
  5.       Create_ServiceStoptextfile();  
  6.    }  
  7.    catch (Exception ex)  
  8.    {  
  9.   
  10.       throw ex;  
  11.    }  
  12.   
  13. }  
Step 8: After that we need to install this service. You can follow my previous article steps for installing window service. How to create Window service.

Step 9: After installation of Window service you can see the following output:

see output