0

我构建了一个应用程序,它使用监听文件夹FileSystemWatcher,当创建一个新文件时,计时器会启动几秒钟,以确保整个文件都在文件夹中。然后我的主 ui 线程的启动事件运行将此文件添加到我的 ListView 中。

成功创建的新文件添加到我的ListView但我的问题是添加第一个后,第二个添加了两次,下一个文件添加了 4 次等等......

我的听众班:

public class FileListener
{
    private static string _fileToAdd;
    public event EventHandler _newFileEventHandler;
    private static System.Timers.Timer _timer;

    public void startListener(string directoryPath)
    {
        FileSystemWatcher watcher = new FileSystemWatcher(directoryPath);
        _timer = new System.Timers.Timer(5000);
        watcher.Filter = "*.pcap";
        watcher.Created += watcher_Created;
        watcher.EnableRaisingEvents = true;
        watcher.IncludeSubdirectories = true;
    }

    void watcher_Created(object sender, FileSystemEventArgs e)
    {            
        _timer.Elapsed += new ElapsedEventHandler(myEvent);
        _timer.Enabled = true;
        _fileToAdd = e.FullPath;
    }

    private void myEvent(object sender, ElapsedEventArgs e)
    {
        _newFileEventHandler(_fileToAdd, EventArgs.Empty);
        _timer.Stop();
    }
}

我处理新文件的事件:

void listener_newFileEventHandler(object sender, EventArgs e)
{
    string file = sender as string;
    addFileToListFiew(file);

}

以及将文件添加到我的功能ListView

public void addFileToListFiew(string file)
{
    this.Invoke((MethodInvoker)delegate
    {
        lvFiles.Items.Add(new ListViewItem(new string[]
        { 
            file, "Waiting"
        }));
    });
}
4

1 回答 1

0
//You can unsubscribe from the previous event subscription using the following:
//You may also need a global boolean variable to keep track of whether or not the watcher currently exists... Although, I am not sure if that is the best resolution for the problem...
watcher.Created -= watcher_Created;

//...

if(eventSubscriptionExists)
{
    //if already subscribed, either do nothing, or re-subscribe

    //unsubscribe from event
    watcher.Created -= watcher_Created;
    //subscribe to event
    watcher.Created += watcher_Created;
}
else
{
    //if not already subscribed to event, start listening for it...
     watcher.Created += watcher_Created;
}
于 2012-12-25T18:59:37.770 回答