先上图,简单的windorm界面;此为最初的版本,后续会增加监听多个源目录的功能、log功能、进度条展示功能等。
1、初始化监听
///
watcher.BeginInit();//设置监听文件类型watcher.Filter = FilterType;//设置是否监听子目录watcher.IncludeSubdirectories = IsInclude;//设置是否启用监听?watcher.EnableRaisingEvents = IsEnableRaising;//设置需要监听的更改类型(如:文件或者文件夹的属性,文件或者文件夹的创建时间;NotifyFilters枚举的内容)watcher.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size;//设置监听的路径watcher.Path = StrWarcherPath;//注册创建文件或目录时的监听事件//watcher.Created += new FileSystemEventHandler(watch_created);//注册当指定目录的文件或者目录发生改变的时候的监听事件watcher.Changed += new FileSystemEventHandler(watch_changed);//注册当删除目录的文件或者目录的时候的监听事件watcher.Deleted += new FileSystemEventHandler(watch_deleted);//当指定目录的文件或者目录发生重命名的时候的监听事件watcher.Renamed += new RenamedEventHandler(watch_renamed);//结束初始化
watcher.EndInit();}
2、启动或者停止监听
///
3、监听以后的事件
///
}private static void watch_changed(object sender, FileSystemEventArgs e){FugaiFile m = new FugaiFile();m.sender = sender;m.e = e;Thread t = new Thread(new ThreadStart(m.C));t.Start();}private static void watch_deleted(object sender, FileSystemEventArgs e){//事件内容MessageBox.Show("监听到删除事件" + e.FullPath);}private static void watch_renamed(object sender, RenamedEventArgs e){FugaiFile m = new FugaiFile();m.sender = sender;m.e = e;Thread t = new Thread(new ThreadStart(m.C));t.Start();}
此处采用多线程的方式去复制文件,下面是复制文件的类
class FugaiFile{public object sender;public FileSystemEventArgs e;public void C(){//MessageBox.Show("监听到修改事件" + e.FullPath);//MessageBox.Show(e.Name + "监听到创建事件" + e.FullPath);String fullname = e.FullPath;string newpath = fullname.Replace(srcPath, TargetPath).Replace("\\" + e.Name, "");DirectoryInfo newFolder = new DirectoryInfo(newpath);if (!newFolder.Exists){newFolder.Create();}FileInfo aa = new FileInfo(e.FullPath);aa.CopyTo(newpath + "\\" + e.Name, true);}}