configuring filesystemwatcher such that it raises created event only when the file is fully copied

半世苍凉 提交于 2019-12-09 01:28:17

问题


When there is a big file moved into the watched folder,it raises created event even before the file is copied fully.

Copying such files within the created event causes 'file being used by another process' error.

I used a thread that tries to copy the file until it is allowed to do so.but i am still not satisfied.

Can we configure FileSystemWatcher such that the created event is raised only after the file is fully copied?thanks.


回答1:


The documentation for the FileSystemWatcher class specifically states your observed behaviour

Common file system operations might raise more than one event. For example, when a file is moved from one directory to another, several OnChanged and some OnCreated and OnDeleted events might be raised. Moving a file is a complex operation that consists of multiple simple operations, therefore raising multiple events. Likewise, some applications (for example, antivirus software) might cause additional file system events that are detected by FileSystemWatcher.

You could check that a lock to the file has been released, and then know that the copying is complete?




回答2:


Why Don't you create your own event that is thrown when the copy is finished by the Thread? You can specify the file and have a method that lisens to the event to handle the post processing.

Details on how to create your own events here: http://msdn.microsoft.com/en-us/library/5z57dxz2.aspx

Because the FileSystemWatcher as discussed by plenderj states that events might be fired you cannot use it. It is really only good for first time creation aka first starts of copy and then the on change will be called possibly numerous times.

EDIT: There is a VB (only) Class that wraps the Windows Copy. You can use this in c# since it all runs off of the clr. This will provide the Windows Dialog to show the progress of the copy.

http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.filesystem.copyfile.aspx

Thanks,

Brad



来源:https://stackoverflow.com/questions/8733816/configuring-filesystemwatcher-such-that-it-raises-created-event-only-when-the-fi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!