I want to create a windows service, which detects if any change(Create, delete or modify)is made to any file in the file system. And when it detects a change, I will check if that change is made to a relevant file. If that is the case, then I will sync the file to the server. I know how I will sync the files, I just want to know how to create an event which fires whenever any change is made to the file system. The event should also provide information, regarding the path of file which was modified ,operation that was performed on the file.
Asked
Active
Viewed 1,924 times
0
-
Look at this answer: http://stackoverflow.com/questions/931093/how-do-i-make-my-program-watch-for-file-modification-in-c it describes also the C# .Net way – Martin Schlott Apr 27 '15 at 07:06
-
possible duplicate of [Directory Modification Monitoring](http://stackoverflow.com/questions/112276/directory-modification-monitoring). **Note:** this is mostly a dupe of that question. However, keep in mind: FSW does not _guarantee_ you'll be notified, and if activity is high on the given file system, it will miss some. The more of the file system you want to monitor (e.g. "_any_ file in the file system"), the more likely it is FSW will miss something. – Peter Duniho Apr 27 '15 at 07:13
1 Answers
1
You just need to initialize FileSystemWatcher and subscribe to relevant events.
FileSystemWatcher watcher = new FileSystemWatcher(@"DirectoryPath");
watcher.Filter = "*.*";//Watch all the files
watcher.EnableRaisingEvents = true;
//Specifies changes to watch for in a file or folder.
watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size;
//Subscribe to the following events
watcher.Changed += new FileSystemEventHandler(watcher_Changed);
watcher.Created += new FileSystemEventHandler(watcher_Created);
watcher.Deleted += new FileSystemEventHandler(watcher_Deleted);
//Raise when new file is created
private void watcher_Created(object sender, FileSystemEventArgs e)
{
//Sync with server
}
//Raise when file is modified
private void watcher_Changed(object sender, FileSystemEventArgs e)
{
//Sync with server
}
//Raise when a file is deleted
private void watcher_Deleted(object sender, FileSystemEventArgs e)
{
//Sync with server
}

Kurubaran
- 8,696
- 5
- 43
- 65
-
Thanx your solution worked with slight modifications. >>In place of directory path I wrote "D:\" to search for whole drive. >>watcher.IncludeSubdirectories = true; so that wacher searches subdirectories too. – V K May 01 '15 at 07:27