0

我有一个简单的C# 控制台应用程序,我在其中使用FileSystemWatcher并在创建文件时将文件从一个目标移动到另一个目标。我的代码如下所示:

    public static void WatchForFiles()
    {
        FileSystemWatcher watcher = new FileSystemWatcher();
        //folder path is path to folder
        watcher.Path = folderPath;

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

        //Add event handlers           
        watcher.Created += new FileSystemEventHandler(File_OnChanged);        

        //Begin watching
        watcher.EnableRaisingEvents = true;
    }


    public static void File_OnChanged(object sender, FileSystemEventArgs e)
    {
        //destiantion path is path to folder
        string destiantionFileFullPath = destianationPath + e.Name;
        if (!File.Exists(destiantionFileFullPath))
        {
            File.Move(e.FullPath, destiantionFileFullPath);
        }
    }

当我第一次复制文件时,它会正常移动。但在那之后,或者如果我复制两个或更多文件,我的控制台窗口会自动关闭。我想我应该使用IAsyncResult但我不知道如何。我尝试了任务,但没有帮助。首先复制文件然后删除也没有帮助。这是什么原因造成的,我该如何预防?提前致谢

4

2 回答 2

1

根据经验,使用 FileWatcher 在文件被转储和(可能)移动时对其进行监控比人们想要管理的麻烦更大。原因很简单,如果在应用程序关闭时文件被转储到目录中,FileWatcher 不会捕获它们。我更喜欢使用定时轮询的计时器,检查目录中是否有文件并移动它们。使用这种方法,如果在应用程序关闭时(例如为了维护)将新文件转储到文件夹中,它们将在应用程序重新启动并且计时器开始轮询时立即移动

于 2012-06-26T11:16:57.847 回答
0

不复制两个文件:当您复制一个文件时,会创建另一个文件,但引发 eventgs 被禁用,因此您不会收到事件通知。

尝试扫描 中的目录File_OnChanged,然后您会发现它。

为什么会退出?我认为它引发了一个异常,可能是 writign 过程尚未完成写入并且您已经在访问该文件 - 这可能是不允许的。

于 2012-06-26T11:05:24.170 回答