1

我的应用程序正在监听目录,并且创建的每个新文件都需要处理,所以我做了一个测试并监听我的文件夹,看看如果我将大文件移动到这个文件夹中,事件会在整个文件创建之前触发,这可以导致我的问题。我可以等到创建所有文件吗?

public void startListener(string directoryPath)
{
    FileSystemWatcher watcher = new FileSystemWatcher(directoryPath);
    watcher.Filter = "*.avi";
    watcher.Created += watcher_Created;
    watcher.EnableRaisingEvents = true;
}

void watcher_Created(object sender, FileSystemEventArgs e)
{

}
4

2 回答 2

0

According the the MSDN docs, multiple OnCreate() and OnChanged() events may be generated when a file is copied from one directory to another.

We need to distinguish two cases here:

  • You are copying the file yourself, so you have control over how the copying is done.

    In this case, it's most efficient to use a temporary filename in the desired folder which does not have the .avi extension (you could for instance use filename.avi.tmp instead of filename.avi), then rename it to the correct name with the .avi extension when you're done copying.

    Then, you subscribe to the Renamed event and watch for files that are renamed to .avi.

  • If you don't have any control over the copying, then you could use one of the techniques described in another answer to this question

于 2012-12-25T14:56:16.997 回答
0

我认为您可以做的是OnCreated通过将“新创建的”文件添加到本地来处理事件List

然后在OnChanged更新片段时触发,检查文件是否在新创建的列表中,并尝试以独占方式打开文件,执行以下操作:

File.Open("someFile.avi", FileMode.Open, FileAccess.Read, FileShare.None)

如果您得到一个IOException,则该文件仍在使用中。

您可以做的另一件事在此评论中描述,使用重命名事件: https ://stackoverflow.com/a/5894697/1373170

事实上,整个 SO 问题可能对您有用: C# FileSystemWatcher,如何知道文件完全复制到监视文件夹中

于 2012-12-25T15:46:48.977 回答