引言
这一周主要精力集中学习一个同事开发的本地文件搜索项目上,其中客户端添加共享文件时主要是使用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); } }