2014-05-22 156 views
2

我的FileSystemWatcher没有抛出任何事件。我已经看过这些类似的问题,似乎没有一个答案是我的问题:FileSystemWatcher不触发事件

*编辑:我的目标是捕获何时将XLS文件复制到或创建在目录中。

Monitor类:

public class Monitor 
{ 
    FileSystemWatcher watcher = new FileSystemWatcher(); 
    readonly string bookedPath = @"\\SomeServer\SomeFolder\"; 

    public delegate void FileDroppedEvent(string FullPath); 
    public event FileDroppedEvent FileDropped; 

    public delegate void ErrorEvent(Exception ex); 
    public event ErrorEvent Error; 

    public Monitor() 
    { 
     watcher.Path = bookedPath; 
     watcher.Filter = "*.xls"; 
     watcher.NotifyFilter = NotifyFilters.LastWrite; 
     watcher.Changed += new FileSystemEventHandler(watcher_Changed); 
     watcher.Error += new ErrorEventHandler(watcher_Error); 
    } 

    void watcher_Error(object sender, ErrorEventArgs e) 
    { 
     Error(e.GetException()); 
    } 

    void watcher_Changed(object sender, FileSystemEventArgs e) 
    { 
     if (e.ChangeType != WatcherChangeTypes.Created) return; 
     FileDropped(e.FullPath); 
    } 

    public void Start() 
    { 
     watcher.EnableRaisingEvents = true; 
    } 

    public void Stop() 
    { 
     watcher.EnableRaisingEvents = false; 
    } 
} 

简单的形式与列表框:

public partial class Form1 : Form 
{ 
    Monitor monitor = new Monitor(); 

    public Form1() 
    { 
     InitializeComponent(); 
     FormClosing += new FormClosingEventHandler(Form1_FormClosing); 
     Load += new EventHandler(Form1_Load); 
     monitor.FileDropped += new Monitor.FileDroppedEvent(monitor_FileDropped); 
     monitor.Error += new Monitor.ErrorEvent(monitor_Error); 
    } 

    void Form1_Load(object sender, EventArgs e) 
    { 
     monitor.Start(); 
    } 

    void Form1_FormClosing(object sender, FormClosingEventArgs e) 
    { 
     monitor.Stop(); 
    } 

    void monitor_Error(Exception ex) 
    { 
     listBox1.Items.Add(ex.Message); 
    } 

    void monitor_FileDropped(string FullPath) 
    { 
     listBox1.Items.Add(FullPath); 
    } 
} 

我在做什么错?

+0

用户代码是否可以访问网络路径运行? – adrianbanks

+0

是的。我正在运行它,我有权访问 – DontFretBrett

+0

您可能会发现以下线程有用:http://stackoverflow.com/questions/11219373/filesystemwatcher-to-watch-unc-path – Edin

回答

-1

你的问题是过滤器以及我相信你的事件。只有打开文件时才会触发NotifyFilters.LastAccess。尝试使用:

NotifyFilters.LastWrite | NotifyFilters.CreationTime 

这将观察写入/创建的文件。接下来,挂接到Created委托来处理新创建的文件:

watcher.Created += YourDelegateToHandleCreatedFiles 

的方式FileSystemWatcher作品是第一次使用NotifyFilters来限制事件触发。然后,你使用实际的事件来完成这项工作。通过连接Created事件,您只能在创建文件时进行工作。

+0

我会试试这个,但我真的只想捕获一个新文件被创建或复制到目录。 – DontFretBrett

+0

然后你只想听'NotifyFilters.LastWrite | NotifyFilters.CreationTime' – Haney

+0

我尝试了你的建议,但它仍然没有开火:/ – DontFretBrett

2

试试看。为我工作的任务非常类似。

watcher.NotifyFilter = NotifyFilters.FileName; 
watcher.Created += new FileSystemEventHandler(handler);  
watcher.Renamed += new RenamedEventHandler(handler); 
+0

试过了,将文件复制到目录中。没有任何事情发生我在watcher_change事件中设置了一个断点,所以它不是我的自定义事件的问题。不过谢谢 – DontFretBrett

0

这可能是因为文件元数据尚未更新。如果您不断写入文件,可能会发生这种情况。