這一周主要精力集中學習一個同事開發的本地文件搜索項目上,其中客戶端添加共享文件時主要是使用FileSystemWatcher 監控文件,並在各種事件發生時向服務器發送消息。
FileSystemWatcher類以前也使用過,沒有太仔細去觀察,這次使用時才發現其事件提示會很有趣:
a):當你添加文件或文件夾時,會觸發Created事件,然後修改默認文件夾或文件名稱再觸發Changed事件。
b):復制或移動文件夾文件時則是觸發Created事件。
c):刪除文件夾或文件時觸發Deleted事件。
注: 重命名事件使用的參數是RenamedEventArgs,而其余事件則是使用FileSystemEventArgs,相應的委托也不同,重命名使用RenamedEventHandler,其余使用FileSystemEventHandler
class Program { static void Main(string[] args) { FileListenerServer f1 = new FileListenerServer(@"D:\TestWatcher"); f1.Start(); Console.ReadKey(); } } public class FileListenerServer { private FileSystemWatcher _watcher; public FileListenerServer() { } public FileListenerServer(string path) { try { this._watcher = new FileSystemWatcher(); _watcher.Path = path; _watcher.NotifyFilter =NotifyFilters.FileName|NotifyFilters.Size|NotifyFilters.DirectoryName; _watcher.IncludeSubdirectories = true; _watcher.Created += new FileSystemEventHandler(FileWatcher_Created); _watcher.Changed += new FileSystemEventHandler(FileWatcher_Changed); _watcher.Deleted += new FileSystemEventHandler(FileWatcher_Deleted); _watcher.Renamed += new RenamedEventHandler(FileWatcher_Renamed); } catch (Exception ex) { Console.WriteLine("Error:"+ex.Message); } } public void Start() { this._watcher.EnableRaisingEvents = true; Console.WriteLine("The Listener Server has started..."); } public void Stop() { this._watcher.EnableRaisingEvents = false; this._watcher.Dispose(); this._watcher = null; } protected void FileWatcher_Created(object sender, FileSystemEventArgs e) { Console.WriteLine("新增:"+e.ChangeType+";"+e.FullPath+";"+e.Name); } protected void FileWatcher_Changed(object sender, FileSystemEventArgs e) { Console.WriteLine("變更:"+e.ChangeType+";"+e.FullPath+";"+e.Name); } protected void FileWatcher_Deleted(object sender, FileSystemEventArgs e) { Console.WriteLine("刪除:" + e.ChangeType + ";" + e.FullPath + ";" + e.Name); } protected void FileWatcher_Renamed(object sender, RenamedEventArgs e) { Console.WriteLine("重命名: OldPath:{0} NewPath:{1} OldFileName{2} NewFileName:{3}",e.OldFullPath,e.FullPath,e.OldName,e.Name); } }