Simulate how to monitor changes to a specified directory.
1. Use Timer to detect changes in folders at intervals, mainly to determine the last time .?
2. Can monitoring be implemented based on the Api or class library provided by the system?
Obviously, it is not scientific or difficult to control the first solution. If timer is used, it will occupy too many resources and cannot clearly locate changes. It is difficult to traverse file changes at a deep level through this method, even if it can be traversed, The traversal will increase the complexity of the system.
However, there isSystem. IO. FileSystemWatcherBy naming, we can see its efficacy-the monitor. As a result, the Demo is compiled based on your own ideas.
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. IO;
Namespace FileWatch
{
Class Program
{
Static void Main (string [] args)
{
// Enter the path to be listened to, for example, c:
String s = Console. ReadLine ();
New FileWatchClass (s );
Console. ReadKey ();
}
}
Class FileWatchClass
{
System. IO. FileSystemWatcher FileWatcher = new FileSystemWatcher ();
Public FileWatchClass (string WatcherPath)
{
FileWatcher. Filter = "*. *"; // sets the file type of the listener.
FileWatcher. Path = WatcherPath; // sets the listening directory.
FileWatcher. Changed + = new FileSystemEventHandler (FileWatcher_Changed); // process the Changed event
FileWatcher. Renamed + = new RenamedEventHandler (FileWatcher_Renamed); // Renamed event processing
FileWatcher. Created + = new FileSystemEventHandler (FileWatcher_Created); // process the Created event
FileWatcher. Deleted + = new FileSystemEventHandler (FileWatcher_Deleted); // ed event processing
FileWatcher. IncludeSubdirectories = true; // sets the listener subdirectory.