先上圖,簡單的windorm界面;此為最初的版本,后續會增加監聽多個源目錄的功能、log功能、進度條展示功能等。
1、初始化監聽
/// <summary> /// 初始化監聽 /// </summary> /// <param name="StrWarcherPath">需要監聽的目錄</param> /// <param name="FilterType">需要監聽的文件類型(篩選器字符串)</param> /// <param name="IsEnableRaising">是否啟用監聽</param> /// <param name="IsInclude">是否監聽子目錄</param> private static void WatcherStrat(string StrWarcherPath, string FilterType, bool IsEnableRaising, bool IsInclude) { //初始化監聽 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、啟動或者停止監聽
/// <summary> /// 啟動或者停止監聽 /// </summary> /// <param name="IsEnableRaising">True:啟用監聽,False:關閉監聽</param> private void WatchStartOrSopt(bool IsEnableRaising) { watcher.EnableRaisingEvents = IsEnableRaising; }
3、監聽以后的事件
/// <summary> /// 創建文件或者目錄時的監聽事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void watch_created(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_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); } }