C#FileSystemWatcher的,如何知道文件完全复制到监视文件夹 [英] C# FileSystemWatcher, How to know file copied completely into the watch folder

查看:597
本文介绍了C#FileSystemWatcher的,如何知道文件完全复制到监视文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发.NET应用程序,在这里我使用FileSystemWatcher类,并附加了创建活动的文件夹。我必须做对这一事件采取行动(如将文件复制到其他位置)。当我把一个大尺寸的进附加监视文件夹时,立即引发竟然还没有完成文件复制过程。我不想用File.open方法的方法进行检查。

I am developing a .net application, where I am using FileSystemWatcher class and attached its Created event on a folder. I have to do action on this event (i.e. copy file to some other location). When I am putting a large size into the attached watch folder the event raised immediately even the file copy process still not completed. I don’t want to check this by file.open method.

有没有办法得到通知,我的文件复制过程到监视文件夹已经完成了,然后我的事件起火。

Is there any way get notify that my file copy process into the watch folder has been completed and then my event get fire.

推荐答案

这确实是一个令人失望的FileSystemWatcher的(和潜在的ReadDirectoryChangesW API)提供了没有办法得到通知时,一个新的文件已经的完全创建。

It is indeed a bummer that FileSystemWatcher (and the underlying ReadDirectoryChangesW API) provide no way to get notified when a new file has been fully created.

解决这个问题的最好和最安全的方式,我已经遇到到目前为止,(那不依赖于定时器)是这样的:

The best and safest way around this that I've come across so far (and that doesn't rely on timers) goes like this:

在接收到创建事件,启动一个线程,在一个循环中,检查文件是否仍然锁定(使用适当的重试间隔和重试计数)。只有这样,才能检查,如果被锁定的文件就是试图以独占访问打开它:如果它成功(没有抛出IOException异常),然后在文件完成复制,而你的线程可以引发相应的事件(如FileCopyCompleted)。

Upon receiving the Created event, start a thread that, in a loop, checks whether the file is still locked (using an appropriate retry interval and maximum retry count). The only way to check if a file is locked is by trying to open it with exclusive access: If it succeeds (not throwing an IOException), then the File is done copying, and your thread can raise an appropriate event (e.g. FileCopyCompleted).

这篇关于C#FileSystemWatcher的,如何知道文件完全复制到监视文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆