先上圖,簡單的windorm界面;此爲最初的版本,後續會增長監聽多個源目錄的功能、log功能、進度條展現功能等。多線程
一、初始化監聽spa
/// <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(); }
二、啓動或者中止監聽線程
/// <summary> /// 啓動或者中止監聽 /// </summary> /// <param name="IsEnableRaising">True:啓用監聽,False:關閉監聽</param> private void WatchStartOrSopt(bool IsEnableRaising) { watcher.EnableRaisingEvents = IsEnableRaising; }
三、監聽之後的事件code
/// <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(); }
此處採用多線程的方式去複製文件,下面是複製文件的類orm
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); } }