Should my FileWatcher also implement IDisposable? I won't be able to use using since this fileWatcher should be watching the file changes the whole time application runs. Would I use Responsible Owner Pattern?(try/finally) or something else? So when using FileSystemWatcher what is the proper way of disposing of FileSystemWatcher? I want FileWatcher not to be disposed/(watching) until application is closed. This is because as soon as a new file is created in the directory being monitored (D:\IDG in our example), the FileSystemWatcher_Created event is triggered.So my understanding is that whenever using a class that implements IDisposable, it's parent also needs to implement IDisposable interface. You would observe that the name of the newly created file is displayed in the console window. Private static void FileSystemWatcher_Created(object sender, FileSystemEventArgs e)Ĭonsole.WriteLine("File created: ", e.Name) Īssuming that the directory named IDG is available on the D:\> drive of your system, run the console application and then create a new file in the IDG directory. In essence, this starts the actual monitoring - you are informing FileSystemWatcher to start monitoring the path and raise appropriate events henceforth.įor each of the events that you have declared, you should have the respective event handler that gets executed when the event is triggered. Here's the source code of the event handlers that would be triggered as and when a change to the directory being monitored occurs. Note how the events are declared and that the EnableRaisingEvents property of the file system watcher object is set to true to enable raising events when a change on the path being monitored occurs. Private static void MonitorDirectory(string path)įileSystemWatcher fileSystemWatcher = new FileSystemWatcher() įileSystemWatcher.Created = FileSystemWatcher_Created įileSystemWatcher.Renamed = FileSystemWatcher_Renamed įileSystemWatcher.Deleted = FileSystemWatcher_Deleted įileSystemWatcher.EnableRaisingEvents = true The directory path is passed as an argument to the method. This method would be used to monitor a particular directory and raise events whenever a change occurs. The following code snippet shows how the MonitorDirectory method would look like. You can build a Windows Service that uses the FileSystemWatcher class and sends out notifications as and when changes occur to the path being watched. Note that a better way to use the FileSystemWatcher class would be by using a Windows Service. Let's create a new console application project in Visual Studio to demonstrate how a typical file system watcher works.
0 Comments
Leave a Reply. |