我在我的C#应用程序(在Windows上运行)上使用FileSystemWatcher
,以便在我的应用程序中更新当前正在浏览的文件。 当我浏览本地目录时,它工作的很好。 当文件被重命名,删除或添加时,我会收到通知。 但是,例如,当我第一次重命名networking驱动器上的文件时, FileSystemWatcher
会通知我一个重命名操作,然后当我重命名同一个文件或另一个文件时, FileSystemWatcher
会通知我一个错误:
the specified server cannot perform the requested operation
。
那么FileSystemWatcher不会通知我任何事情。
有时我可以重命名两次FileSystemWatcher之前不通知我什么…
这是我的testing代码:
static void Main(string[] args) { FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = @"N:\prive\defFolder"; watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite; watcher.Changed += new FileSystemEventHandler(watcher_Changed); watcher.Created += new FileSystemEventHandler(watcher_Changed); watcher.Deleted += new FileSystemEventHandler(watcher_Changed); watcher.Renamed += new RenamedEventHandler(watcher_Renamed); watcher.Error += new ErrorEventHandler(watcher_Error); watcher.EnableRaisingEvents = true; Console.Read(); watcher.Dispose(); } static void watcher_Error(object sender, ErrorEventArgs e) { Console.WriteLine("error : " + e.GetException().Message); } static void watcher_Renamed(object sender, RenamedEventArgs e) { Console.WriteLine("rename success"); } static void watcher_Changed(object sender, FileSystemEventArgs e) { Console.WriteLine("change success"); }
首先,远程共享的文件系统监控总是会有些不可靠。 您不应该依赖您的应用程序来获取所有事件 – 事实上,我建议您提供一个备用轮询机制来检查您可能错过的更改。 GUI中的刷新按钮可能是另一种选择,具体取决于您的应用程序。
这就是说,你的特殊问题似乎并不罕见。 我搜索了一下,发现了这些东西:
我的猜测是,这是Samba与Windows结合的某些版本(或配置)的问题。 Linux服务器上的Samba日志中是否有可能指出问题的原因?
作为一个直接的解决办法,我建议你尝试这些东西:
EnableRaisingEvents
在获取错误时是否设置为false
– 也许您可以将其设置为true以再次开始接收事件。 if (Directory.Exists(monitorPath)) { watcher.Path = monitorPath; watcher.IncludeSubdirectories = true; watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.CreationTime; watcher.InternalBufferSize = 65536; watcher.Filter = "test_prod-Pg1_ICT*"; watcher.Changed += new FileSystemEventHandler(fileChangedEvent); watcher.EnableRaisingEvents = true; LogEvent("Folder Syncronization Service is Started!"); }
我创建了基于Window Service FileSystemWatcher的类来监视Samba共享文件夹onChanges,并使用CodeProject中的DifferenceEngine检查不同的内容,如果有更改,则复制到Window Shared Folder Path。 我还添加了一个定时器来检查网络失败时每10秒处理一次。 有一个列表数组来存储更改计数。 当文件改变事件被提出时被添加到列表中并且当成功时移除列表。
我在Window 7 Pro OS上测试了两台惠普笔记本电脑,工作正常。
但未能在其他Windows 7 Pro笔记本电脑和Windows XP专业版SP3桌面上工作。 (我们在同一个公司网络/ VLAN和服务包)
失败的意思是如果我修改了Samba共享文件夹中的某些内容,它不会将最新的内容同步到Window Share Path。
我也加了这些
[PermissionSetAttribute(SecurityAction.LinkDemand,Name =“FullTrust”)] [PermissionSetAttribute(SecurityAction.InheritanceDemand,Name =“FullTrust”)]
在编码的顶部,它似乎不起作用