在实际工作中,我们经常有需要监控部分文件或文件夹更改的需求。这时候,FileSystemWatcher就派上用场了。
首先我们new一个FileSystemWatcher实例
FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();
然后我们可以通过设置Path来指定一个监视目录。
fileSystemWatcher.Path = @"D:\test";
注意,这里只能是一个目录,而不能是一个文件。
那么如果我们只想监视某个文件怎么办呢?
可以设置Filter来指定只监控某种类型的文件,或者某个文件。
fileSystemWatcher.Filter = "*.txt";
设置只监控txt文件,也可以设置成test.txt
,这样就只监控text.txt这一个文件。
设置是否同时监控子目录
fileSystemWatcher.IncludeSubdirectories = true;
true
为监控子目录。
还可以设置监听哪些改变
fileSystemWatcher.NotifyFilter = NotifyFilters.Attributes
| NotifyFilters.CreationTime
| NotifyFilters.DirectoryName
| NotifyFilters.FileName
| NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.Security
| NotifyFilters.Size;
NotifyFilters的具体含义如下:
监控事件分为Changed
、Created
、Deleted
、Renamed
、Error
五种。
fileSystemWatcher.Changed += OnChanged;
fileSystemWatcher.Created += OnCreated;
fileSystemWatcher.Deleted += OnDeleted;
fileSystemWatcher.Renamed += OnRenamed;
fileSystemWatcher.Error += OnError;
简易使用如下:
private static void OnChanged(object sender, FileSystemEventArgs e)
{
if (e.ChangeType != WatcherChangeTypes.Changed)
{
return;
}
Console.WriteLine($"Changed: {e.FullPath}");
}
private static void OnCreated(object sender, FileSystemEventArgs e)
{
string value = $"Created: {e.FullPath}";
Console.WriteLine(value);
}
private static void OnDeleted(object sender, FileSystemEventArgs e) =>
Console.WriteLine($"Deleted: {e.FullPath}");
private static void OnRenamed(object sender, RenamedEventArgs e)
{
Console.WriteLine($"Renamed:");
Console.WriteLine($" Old: {e.OldFullPath}");
Console.WriteLine($" New: {e.FullPath}");
}
private static void OnError(object sender, ErrorEventArgs e) =>
PrintException(e.GetException());
private static void PrintException(Exception? ex)
{
if (ex != null)
{
Console.WriteLine($"Message: {ex.Message}");
Console.WriteLine("Stacktrace:");
Console.WriteLine(ex.StackTrace);
Console.WriteLine();
PrintException(ex.InnerException);
}
}
最后,我们需要设置
fileSystemWatcher.EnableRaisingEvents = true;
来启用监听,这时候如果有更改,就会触发对应的事件了。