C# monitors file system changes (FileSystemWatcher)

FileSystemWatcher is often used to monitor changes in files or folders in the file system.

1. Common events

Changed: Triggered when the file or folder is modified
Created: Triggered when the file or folder is successfully created
Deleted: When the file or folder is successfully created Triggered when the folder is successfully deleted
Renamed: Triggered when the file or folder is renamed
Error: Triggered when an error occurs during the change process

2. Basic attributes

(1) Path: Set the path of the directory to be monitored.
(2) IncludeSubdirectories: Set whether to cascade monitor subdirectories in the specified path.
(3) Filter: Set the filter string to determine which types of files are monitored in the directory.
(4) NotifyFilter: Set which attribute changes of the file will trigger the Changed event. Monitoring multiple attribute changes at the same time can be combined by pressing "or". (The default value is the combination of NotifyFilter.LastWrite | NotifyFilter.FileName | NotifyFilter.DirectoryName)
(5) EnableRaisingEvents: Set whether to start monitoring. (default is false)

The properties of NotifyFilters are as follows:

attribute name mean
Attributes File or folder properties
CreationTime The creation time of the file or folder
DirectoryName directory name
FileName file name
LastAccess The date the file or folder was last opened
LastWrite The date when something was last written to the file or folder
Security Security settings for files or folders
Size File or folder size

3. Code examples

    private static void FileWatcher(string path, string filter)
    {
    
    
      FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();
      fileSystemWatcher.Path = path;
      fileSystemWatcher.NotifyFilter = NotifyFilters.LastAccess 
                                     | NotifyFilters.LastWrite 
      								 | NotifyFilters.FileName 		   
      								 |NotifyFilters.DirectoryName;
       //文件类型,支持通配符,“*.txt”只监视文本文件
      fileSystemWatcher.Filter = filter;    // 监控的文件格式
      watch.IncludeSubdirectories = true;  // 监控子目录
      fileSystemWatcher.Changed += new FileSystemEventHandler(OnProcess);
      fileSystemWatcher.Created += new FileSystemEventHandler(OnProcess);
      fileSystemWatcher.Renamed += new RenamedEventHandler(OnRenamed);
      fileSystemWatcher.Deleted += new FileSystemEventHandler(OnProcess);
      //表示当前的路径正式开始被监控,一旦监控的路径出现变更,FileSystemWatcher 中的指定事件将会被触发。
      fileSystemWatcher.EnableRaisingEvents = true;
    }
	private static void OnProcess(object source, FileSystemEventArgs e)
	{
    
    
    	if (e.ChangeType == WatcherChangeTypes.Created)
    	{
    
    
          	OnCreated(source, e);
   		}
    	else if (e.ChangeType == WatcherChangeTypes.Changed)
    	{
    
    
          	OnChanged(source, e);
    	}
    	else if (e.ChangeType == WatcherChangeTypes.Deleted)
    	{
    
    
          	OnDeleted(source, e);
    	} 
	}

	private static void OnCreated(object source, FileSystemEventArgs e)
    {
    
    
      Console.WriteLine("File created: {0} {1} {2}", e.ChangeType, e.FullPath, e.Name);
    }

    private static void OnChanged(object source, FileSystemEventArgs e)
    {
    
    
      Console.WriteLine("File changed: {0} {1} {2}", e.ChangeType, e.FullPath, e.Name);
    }

    private static void OnDeleted(object source, FileSystemEventArgs e)
    {
    
    
      Console.WriteLine("File deleted: {0} {1} {2}", e.ChangeType, e.FullPath, e.Name);
    }

	private static void OnRenamed(object source, FileSystemEventArgs e)
    {
    
    
      Console.WriteLine("File renamed: {0} {1} {2}", e.ChangeType, e.FullPath, e.Name);
    }

Summarize

1. Renaming will trigger two events, Renamed and Changed.
2. The FileSystemWatcher class itself is a multi-threaded control. Each time a FileSystemWatcher is instantiated, a thread is automatically created.
3. Create, modify, and delete events pass FileEventArgs objects, while rename events pass RenameEventArgs objects.
4. If you need to monitor multiple files at the same time, you need to create a FileSystemWatcher array and use one FileSystemWatcher for monitoring each file.

DateTime Microsoft official documentation

Guess you like

Origin blog.csdn.net/qq_38318701/article/details/128406759