Use FileSystemWatcher to monitor folders and files,
Introduction
This week, I focused on a local file search project developed by my colleagues. When a client adds shared files, I mainly use the FileSystemWatcher monitoring file and send messages to the server when various events occur.
Solution
The FileSystemWatcher class has been used before and has not been carefully observed. This time, we found that the event prompt will be very interesting:
A): When you add a file or folder, the Created event is triggered, and the default folder or file name is modified to trigger the Changed event.
B): The Created event is triggered when the folder file is copied or moved.
C): The Deleted event is triggered when a folder or file is Deleted.
Note: RenamedEventArgs is used for renaming events, while FileSystemEventArgs is used for other events, and different delegates are used. RenamedEventHandler is used for renaming events, and FileSystemEventHandler is used for others.
Code
Class Program {static void Main (string [] args) {FileListenerServer f1 = new FileListenerServer (@ "D: \ TestWatcher"); f1.Start (); Console. readKey () ;}} public class FileListenerServer {private FileSystemWatcher _ watcher; public FileListenerServer () {} public FileListenerServer (string path) {try {this. _ watcher = new FileSystemWatcher (); _ watcher. path = path; _ watcher. policyfilter = policyfilters. fileName | policyfilters. size | policyfilters. directoryName; _ watcher. includeSubdirectories = true; _ watcher. created + = new FileSystemEventHandler (FileWatcher_Created); _ watcher. changed + = new FileSystemEventHandler (FileWatcher_Changed); _ watcher. deleted + = new FileSystemEventHandler (FileWatcher_Deleted); _ watcher. renamed + = new RenamedEventHandler (FileWatcher_Renamed);} catch (Exception ex) {Console. writeLine ("Error:" + ex. message) ;}} public void Start () {this. _ watcher. enableRaisingEvents = true; Console. writeLine ("The Listener Server has started... ");} public void Stop () {this. _ watcher. enableRaisingEvents = false; this. _ watcher. dispose (); this. _ watcher = null;} protected void FileWatcher_Created (object sender, FileSystemEventArgs e) {Console. writeLine ("add:" + e. changeType + ";" + e. fullPath + ";" + e. name);} protected void FileWatcher_Changed (object sender, FileSystemEventArgs e) {Console. writeLine ("Change:" + e. changeType + ";" + e. fullPath + ";" + e. name);} protected void FileWatcher_Deleted (object sender, FileSystemEventArgs e) {Console. writeLine ("delete:" + e. changeType + ";" + e. fullPath + ";" + e. name);} protected void FileWatcher_Renamed (object sender, RenamedEventArgs e) {Console. writeLine ("RENAME: OldPath: {0} NewPath: {1} OldFileName {2} NewFileName: {3}", e. oldFullPath, e. fullPath, e. oldName, e. name );}}