Using FileSystemWatcher to Monitor a Directory

I am using a Windows Forms application to monitor a directory and move files falling into it to another directory.

At the moment, it will copy the file to another directory, but when another file is added, it simply will not end the error message. Sometimes it copies two files until the end of the third.

Is it because I'm using a Windows Form application and not a console application? Is there any way to stop the program and continue browsing the directory?

private void watch() { FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = path; watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; watcher.Filter = "*.*"; watcher.Changed += new FileSystemEventHandler(OnChanged); watcher.EnableRaisingEvents = true; } private void OnChanged(object source, FileSystemEventArgs e) { //Copies file to another directory. } 
+56
c # io copy winforms filesystemwatcher
Feb 22 '13 at 5:30
source share
3 answers

The problem was notification filters. The program tried to open the file that was still copying. I removed all notification filters except LastWrite.

 private void watch() { FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = path; watcher.NotifyFilter = NotifyFilters.LastWrite; watcher.Filter = "*.*"; watcher.Changed += new FileSystemEventHandler(OnChanged); watcher.EnableRaisingEvents = true; } 
+79
Mar 06 '13 at 15:40
source share

You did not submit the file processing code, but I assume that you made the same mistake as everyone when writing such a thing: the filewatcher event will be raised as soon as the file is created. However, it will take some time to complete the file. For example, take a 1 GB file. The file may be created by another program (Explorer.exe copies it from somewhere), but it takes several minutes to complete this process. The event occurs during creation, and you need to wait until the file is ready for copying.

You can wait until the file is ready using this function in a loop.

+20
Feb 22 '13 at 6:18
source share

The reason may be that the observer is declared as a local variable for the method, and this is garbage collection when the method ends. You must declare it a member of the class. Try the following:

 FileSystemWatcher watcher; private void watch() { watcher = new FileSystemWatcher(); watcher.Path = path; watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; watcher.Filter = "*.*"; watcher.Changed += new FileSystemEventHandler(OnChanged); watcher.EnableRaisingEvents = true; } private void OnChanged(object source, FileSystemEventArgs e) { //Copies file to another directory. } 
+13
Feb 22 '13 at 6:18
source share



All Articles