📅  最后修改于: 2023-12-03 15:13:48.911000             🧑  作者: Mango
The FileSystemWatcher
class in C# allows you to monitor changes to a file or directory. It can be used to detect when a file is created, deleted, or modified. This is useful for applications that need to know when a file has changed, such as log file readers or document management systems.
To use FileSystemWatcher
, you must first create an instance of the class and configure it using various properties such as Path
, Filter
, and NotifyFilter
. Here is an example of how to set up a basic FileSystemWatcher
:
using System.IO;
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"C:\Users\Username\Desktop";
watcher.Filter = "*.txt";
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Changed += OnChanged;
watcher.EnableRaisingEvents = true;
private static void OnChanged(object source, FileSystemEventArgs e)
{
Console.WriteLine("File Changed: " + e.FullPath);
}
In this example, the watcher is set up to monitor the desktop directory of the current user, looking for changes to any text file (*.txt
). It is configured to only notify when the last write time of the file is changed. The Changed
event is subscribed to, which will be triggered whenever a file matching the filter is changed.
When a change is detected, the Changed
event will be raised. This event exposes a FileSystemEventArgs
object, which contains information about the change that occurred. The four types of changes that can be detected are created (Created
), changed (Changed
), deleted (Deleted
), and renamed (Renamed
).
You can handle each of these events by subscribing to the corresponding event. Here is an example of how to handle the Created
event:
watcher.Created += OnCreated;
private static void OnCreated(object source, FileSystemEventArgs e)
{
Console.WriteLine("File Created: " + e.FullPath);
}
While FileSystemWatcher
is a powerful tool, it does have certain limitations. The most important limitation is that it is not always reliable. For example, it may miss some events due to timing issues. Additionally, some operations (such as renaming a file) can trigger multiple events, which can be difficult to handle.
Another limitation is that the FileSystemWatcher
can only monitor local file systems. It does not work over a network (although it can monitor a network share if it's mapped to a drive letter).
In conclusion, FileSystemWatcher
in C# is a useful tool for monitoring changes to files and directories. While it has its limitations, it can be a powerful addition to any application that needs to keep track of changes to files.