大家好,又见面了,我是你们的朋友全栈君。
本文测试了FileSystemWatcher 类监控文件变化。
using System;
using System.Security.Permissions;
using System.IO;
namespace ConsoleApp1
{
public class FileStateWatcher
{
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public static int Run()
{
FileSystemWatcher fsWatcher = new FileSystemWatcher();
fsWatcher.Path = "E:\\Test";
fsWatcher.NotifyFilter = NotifyFilters.LastAccess | //上一次打开的日期。
NotifyFilters.LastWrite | //上一次写入内容的日期
NotifyFilters.FileName | //文件名
NotifyFilters.DirectoryName | //目录名
NotifyFilters.Size; //大小
//监听子目录
fsWatcher.IncludeSubdirectories = true;
//监听文件类型
fsWatcher.Filter = "*.txt";
//添加事件处理
fsWatcher.Changed += new FileSystemEventHandler(OnChanged);
fsWatcher.Created += new FileSystemEventHandler(OnCreated);
fsWatcher.Deleted += new FileSystemEventHandler(OnDeleted);
fsWatcher.Renamed += new RenamedEventHandler(OnRenamed);
fsWatcher.EnableRaisingEvents = true;
return 0;
}
//修改时的处理
private static void OnChanged(Object source, FileSystemEventArgs e)
{
Console.WriteLine("File: {0} {1}", e.FullPath, e.ChangeType);
}
//重命名时的处理
private static void OnRenamed(Object source, FileSystemEventArgs e)
{
Console.WriteLine("File: {0} {1}", e.FullPath, e.ChangeType);
}
//删除时的处理
private static void OnDeleted(object source, FileSystemEventArgs e)
{
Console.WriteLine("File: {0} {1}", e.FullPath, e.ChangeType);
}
//创建时的处理
private static void OnCreated(object source, FileSystemEventArgs e)
{
Console.WriteLine("File: {0} {1}", e.FullPath, e.ChangeType);
}
};
class Program
{
static void Main(string[] args)
{
FileStateWatcher.Run();
// 输入q结束程序
Console.WriteLine("Press q to quit the sample.");
while (Console.Read() != 'q') ;
}
}
}
上例中监控的目录是“E:\\Test”,在此目录下创建txt文件,命名为“log.txt”
运行结果:
本例仅仅打印了发生变化的文件名及变化类型。
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/149390.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...