Friday, June 6, 2014

FileSystemWatcher C#

Short example how to implement the FileSystemWatcher class.


In my example I´ve used a empty windows forms application.

First stepp, add a textbox and a button to the form.












Next we will implement the FileSystemWatcher class.
I´ve used in this example the Start button to initialize the FileSystemWatcher class.











I´ve created the FileSystemWatcher class to monitor a local path.

With watcher.Created += watcherEventwatcher.Deleted += watcherEvent and watcher.Renamed += watcherEvent we will create three events.
The first event will happen if a new file is created in this folder. (watcher.Created += watcherEvent)
The second event will happen if a file is deleted in this folder. (watcher.Deleted += watcherEvent)
The third event will happen if a file is renamed in this folder. (watcher.Renamed += watcherEvent)


As next step we have to create the watcherEvent function.



















Within this function we will handle all three events.
In my example, I will just write the event name to the text box.

Therefore we have to implement a delegate.
This is necessary because the FileSystemWatcher is running in the background as separate thread and it is not possible to update a object in the form from a new sub thread.

To handle this, I´ve created a function called "UpdateWatcherOutput" and also the delegate UpdateWatcherOutputCallback.

In this function we can update the text box with the event name.

In the event function from the FileSystemWatcher we will check if a Invoke is required. (WatcherOutputTextBox.InvokeRequired)

If YES, we will create a new delegate UpdateWatcherOutputCallback and will invoke it.


Now you can start the application and with the Start button the FileSystemWatcher will start with his work.
When you now create, delete or rename a file in the defined path, you will see the event name in the text box.


Have fun :-)

Kind regards,
FreaksOfDeveloper


Blogverzeichnis blogwolke.de - Das Blog-Verzeichnis Icon RSS Newsfeed Verzeichnis Web-Feed.de Blogverzeichnis FreakDeveloper Contributes to DaniWeb Blogtotal Foxload TopBlogs.de das Original - Blogverzeichnis | Blog Top Liste

No comments:

Post a Comment