Click here to Skip to main content
15,887,861 members
Articles / Programming Languages / C#

Using FileSystemWatcher to Monitor Multiple Directories

Rate me:
Please Sign up or sign in to vote.
4.71/5 (6 votes)
20 Oct 2011CPOL 57.2K   29   7
There are times when we need to monitor multiple directories and if any changes are available, invoke a given method.

In a previous example, I showed how to use the FileSystemWatcher class to monitor a directory. But there are times when we need to monitor multiple directories and if any changes are available, invoke a given method.

We can do that by using the following method. First create a class. We’ll call this class Watcher.

C#
 1: public class Watcher
 2:     {
 3:         public string Directory { get; set; }
 4:         public string  Filter { get; set; }   6:
 5:
 6:         private Delegate _changeMethod;
 7:
 8:         public Delegate ChangeMethod
 9:         {
10:             get { return _changeMethod; }
11:             set { _changeMethod = value; }
12:         }
13:
14:         FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();
15:
16:         public Watcher(string directory, string filter, Delegate invokeMethod)
17:         {
18:             this._changeMethod = invokeMethod;
19:             this.Directory = directory;
20:             this.Filter = filter;
21:         }
22:
23:         public void StartWatch()
24:         {
25:             fileSystemWatcher.Filter = this.Filter;
26:             fileSystemWatcher.Path = this.Directory;
27:             fileSystemWatcher.EnableRaisingEvents = true;
28:
29:             fileSystemWatcher.Changed +=
                  new FileSystemEventHandler(fileSystemWatcher_Changed);
30:         }
31:
32:         void fileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
33:         {
34:             if (_changeMethod != null)
35:             {
36:                 _changeMethod.DynamicInvoke(sender, e);
37:             }
38:         }
39:     }

And we can use it to monitor multiple directories as shown below (for this example, I have used a console application and I am only considering the change event):

C#
 1: class Program
 2:     {
 3:         delegate void invokeMethodDelegate(object sender, FileSystemEventArgs e);
 4:
 5:         static void Main(string[] args)
 6:         {
 7:             invokeMethodDelegate mymethod = new invokeMethodDelegate(InvokeMethod);
 8:             Watcher w1 = new Watcher(@"C:\Directory1", "*.*", mymethod);
 9:             w1.StartWatch();
10:
11:             Watcher w2 = new Watcher(@"D:\Directory2", "*.*", mymethod);
12:             w2.StartWatch();
13:
14:             string zRetVal = Console.ReadLine();
15:         }
16:
17:         static  void InvokeMethod(object sender, FileSystemEventArgs e)
18:         {
19:             Console.WriteLine("Change in file {0}", e.FullPath);
20:         }
21:     }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead Air Liquide Industrial Services (Singapore)
Singapore Singapore
My passion lies in building business intelligence and data-based solutions, writing about things I work with and talking about it. New technologies relevant to my line of work interest me and I am often seen playing with early releases of such technologies.

My current role involves architecting and building a variety of data solutions, providing database maintenance and administration support, building the organization’s data practice, and training and mentoring peers.

My aspiration over the next several years is to achieve higher competency and recognition in the field of Data Analytics and move into a career of data science.


Specialities: SQL Server, T-SQL Development, SQL Server Administration, SSRS, SSIS, C#, ASP.Net, Crystal Reports

Comments and Discussions

 
PraiseWorking Perfectly Pin
Pinto E Anto4-Apr-20 21:02
Pinto E Anto4-Apr-20 21:02 
If any one interested in VB.net code. Below is the tested one.
Class Declaration
VB
Public Class Watcher
        Public Property Directory As String
        Public Property Filter As String
        Private _changeMethod As [Delegate]
        Public Property ChangeMethod As [Delegate]
            Get
                Return _changeMethod
            End Get
            Set(ByVal value As [Delegate])
                _changeMethod = value
            End Set
        End Property
        Private fileSystemWatcher As FileSystemWatcher = New FileSystemWatcher()
        Public Sub New(ByVal directory As String, ByVal filter As String, ByVal invokeMethod As [Delegate])
            Me._changeMethod = invokeMethod
            Me.Directory = directory
            Me.Filter = filter
        End Sub

        Public Sub StartWatch()
            fileSystemWatcher.Filter = Me.Filter
            fileSystemWatcher.Path = Me.Directory
            fileSystemWatcher.EnableRaisingEvents = True
            AddHandler fileSystemWatcher.Changed, New FileSystemEventHandler(AddressOf fileSystemWatcher_Changed)
        End Sub
        Private Sub fileSystemWatcher_Changed(ByVal sender As Object, ByVal e As FileSystemEventArgs)
            If _changeMethod IsNot Nothing Then
                _changeMethod.DynamicInvoke(sender, e)
            End If
        End Sub
    End Class

Implementation to iterate to multiple folders from Json file stored in <applicationdirectorypath>\_bin\_config\_fw.json
VB
    Delegate Sub invokeMethodDelegate(ByVal sender As Object, ByVal e As FileSystemEventArgs)
    Dim _IntegrationFiles As IntegrationFiles = New IntegrationFiles
    Public Sub _Fn_StartMultipleFolderWatch() 'Call this Sub to start the watch
        Dim mymethod As invokeMethodDelegate = New invokeMethodDelegate(AddressOf InvokeMethod)
        _IntegrationFiles = JsonConvert.DeserializeObject(Of IntegrationFiles)(IO.File.ReadAllText(DP + "\_bin\_config\_fw.json")) 'Read configuration from json.
        For Each _folder As Folder In _IntegrationFiles.Folders 'iterate through the configuration and assigning folders to watch
            Console.WriteLine("File watch initiated for " + _folder.Name + ": \\" + _folder.IP + "\" + _folder.Folder + "\")
            Dim Watcher1 As Watcher = New Watcher("\\" + _folder.IP + "\" + _folder.Folder, "*.*", mymethod)
            Watcher1.StartWatch()
        Next
        Dim zRetVal As String = Console.ReadLine()
    End Sub

    Private Sub InvokeMethod(ByVal sender As Object, ByVal e As FileSystemEventArgs)
        Console.WriteLine("Change in file {0}", e.FullPath)
' <Write any code here to execute when any activity is captured>
    End Sub

Json File to be saved as fw.json in local folder mentioned above.
JavaScript
{
  "Folders": [
    {
      "Name": "CMSIntegration",
      "IP": "192.168.86.31",
	  "Folder": "integration",
      "iFiles": [
        {
          "Name": "Actual.txt",
   		  "Descritpion":"Contains CMS Equipment faults",
          "Fn": ""
        },
        {
          "Name": "uptime.txt",
		  "Descritpion":"Contains Server Status and uptime details",
          "Fn": ""
        }
      ]
    },
  {
      "Name": "GOS",
      "IP": "192.168.86.31",
	  "Folder": "GOS",
      "iFiles": [
        {
          "Name": "GOSFault.txt",
		  "Descritpion":"Contains GOS faults details",
          "Fn": ""
        },
        {
          "Name": "GOSDock.txt",
		  "Descritpion":"Contains Docking details",
          "Fn": ""
        }
      ]
    }
  ]
}

Json Class Declaration for de-serializing
VB
Public Class iFile
    Public Property Name As String
    Public Property Descritpion As String
    Public Property Fn As String
End Class

Public Class Folder
    Public Property Name As String
    Public Property IP As String
    Public Property Folder As String
    Public Property iFiles As List(Of iFile)
End Class

Public Class IntegrationFiles
    Public Property Folders As List(Of Folder)
End Class


Thanks
inst : pintoorion

QuestionService version? Pin
Dan Oviatt26-Jun-12 10:28
Dan Oviatt26-Jun-12 10:28 
AnswerRe: Service version? Pin
Manjuke Fernando26-Jun-12 16:19
professionalManjuke Fernando26-Jun-12 16:19 
GeneralRe: Service version? Pin
Dan Oviatt27-Jun-12 3:19
Dan Oviatt27-Jun-12 3:19 
GeneralRe: Service version? Pin
justmicros13-Nov-12 9:57
justmicros13-Nov-12 9:57 
GeneralRe: Service version? Pin
Manjuke Fernando13-Nov-12 13:33
professionalManjuke Fernando13-Nov-12 13:33 
Questionvery interesting artice Pin
mike231521-Oct-11 2:32
mike231521-Oct-11 2:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.