1.在WinForm中 加入FileSystemWatcher控件
2.实例化FileSystemWatcher对象
public void FileWatche()
{
FileSystemWatcher watch = new FileSystemWatcher();
watch.Path = @""; //监控的路径
watch.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName |
NotifyFilters.DirectoryName;
watch.Filter = "*.*"; // 监控的文件格式
watch.IncludeSubdirectories = true; // 监控子目录
watch.Created += new FileSystemEventHandler(OnCreatedFile); // 有文件创建则触发事件(watch.Created)
watch.Changed += new FileSystemEventHandler(OnChangedFile); //有文件改變則觸發事件(watch.Changed)
watch.EnableRaisingEvents = true; // 启动监控
}
//监控多种格式的文件
public void FileWatche()
{
string[] filters = { "*.BMP", "*.JPG", "*.PNG" };
foreach (string f in filters)
{
FileSystemWatcher pwc = new FileSystemWatcher();
pwc.Path = @""; //监控的路径
pwc.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName |
NotifyFilters.DirectoryName;
pwc.Filter = f; // 监控的文件格式
pwc.IncludeSubdirectories = true; // 监控子目录
pwc.Created += new FileSystemEventHandler(OnCreatedFile); // 有文件创建则触发事件(watch.Created)
watch.Changed += new FileSystemEventHandler(OnChangedFile); //有文件改變則觸發事件(watch.Changed)
pwc.EnableRaisingEvents = true; // 启动监控
}
}
3文件触发事件
//文档发生改变的是时候,读取数据
private void OnChangedFile(object sender, FileSystemEventArgs e)
{
string FilePath = e.FullPath;//文件地址
string FileName = e.Name;//文件名
(sender as FileSystemWatcher).EnableRaisingEvents = false;
//設置讀取時間,当监测文件改变等待指定的时间才开始读取
setInternal(FileName,FilePath);
(sender as FileSystemWatcher).EnableRaisingEvents = true;//这样可以保证changed事件可以被重新触发。
}
4定时执行
public void setInternal(string name,string path)
{
System.Timers.Timer timer;
this.timer = new System.Timers.Timer(9000);//实例化Timer类,设置时间间隔
timer.Elapsed += new System.Timers.ElapsedEventHandler((s, e) => copy(s, e, name, path));//当到达时间的时候执行事件
timer.AutoReset =false ;//false是执行一次,true是一直执行,当为true时会导致只监测一个文档
timer.Enabled = true;//设置是否执行System.Timers.Timer.Elapsed事件
}
5执行文件读取
public void copy(object source, ElapsedEventArgs e, string name1, string name2)
{
//需要执行的操作
}