在按下退出按钮之前,如何继续观看目录?

时间:2012-03-07 16:32:28

标签: loops filesystemwatcher

提前感谢,对于大多数人来说,这很简单,但我不熟悉编程。

我的第一个应用程序是一个winform应用程序,允许用户选择一个目录,当他们点击start时,会初始化FileSystemWatcher。所有的工作,我已经处理了更改,删除等,但我的问题是,它只处理一个事件(虽然正确)但在此之后它关闭。

我需要设置

Watcher.EnableRaisingEvents=True

直到按下退出按钮?

这里的代码目前是:

public void btnStart(object sender, EventArgs e)
    {
        //create watcher and set properties

        FileSystemWatcher Watcher1 = new FileSystemWatcher();

        Watcher1.Path = txtBoxDirToWatch.Text;

        if (Watcher1.Path.Length <2)
        {
            MessageBox.Show("Path does not exist, Please reselect");
            return;
        }

        //user response to close
        MessageBox.Show("Your directory is now being monitored for changes");

        Watcher1.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;

        //watch all files in the path 

        Watcher1.Filter = "*.*";

        //add event handlers

        Watcher1.Changed += new FileSystemEventHandler(OnChanged);
        Watcher1.Created += new FileSystemEventHandler(OnChanged);
        Watcher1.Deleted += new FileSystemEventHandler(OnDeleted);
        Watcher1.Renamed += new RenamedEventHandler(OnRenamed);

        //begin watching

        Watcher1.EnableRaisingEvents = true;    

    }

    public static void OnChanged(object source, FileSystemEventArgs e)

    {

        //need something in here to deal with changes and copy to hidden directory

        string destination = Path.Combine(@"C:\Watcher\sync", e.Name);

        File.Copy(e.FullPath, destination);

   }

    public static void OnRenamed(object source, FileSystemEventArgs e)
    {

然后我处理onrenamed,ondeleted等

有人能说出正确的方向吗?

由于

1 个答案:

答案 0 :(得分:0)

这里的解决方案是为每个程序启动创建一个新线程,并在每个线程上设置EnableRaisingEvents = new。

new Thread(ReNamed).Start(); new Thread(Changed).Start(); new Thread(Deleted).Start(); new Thread(Created).Start();

void ReNamed()
    {
        FileSystemWatcher Watcher2 = new FileSystemWatcher();

        Watcher2.Path = txtBxDirToWatch.Text;
        Watcher2.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName;// | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.DirectoryName;

        //watch all files in the path 

        Watcher2.Filter = "*.*";

        //dont watch subdirectories as default
        Watcher2.IncludeSubdirectories = false;
        if (chkBxIncSub.Checked)
        {
        Watcher2.IncludeSubdirectories = true;
        }

        Watcher2.Renamed += new RenamedEventHandler(OnRenamed);
        Watcher2.EnableRaisingEvents = true;
    }