FileSystemWatcher的 - 是文件准备好使用 [英] FileSystemWatcher - is File ready to use

查看:100
本文介绍了FileSystemWatcher的 - 是文件准备好使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当一个文件被复制到文件夹守望者,我怎么能确定文件是否被完全复制,并准备使用?因为我在文件拷贝越来越多的事件。 (该文件是通过使用File.Copy另一个程序复制。)

When a file is being copied to the file watcher folder, how can I identify whether the file is completely copied and ready to use? Because I am getting multiple events during file copy. (The file is copied via another program using File.Copy.)

推荐答案

当我遇到了这个问题,我想出了最好的解决办法就是不断地尝试,以取得该文件的独占锁;而该文件正被写入时,锁定的尝试将失败,基本上在<一个的方法href="http://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-is-in-use">this回答。一旦该文件不被写入到任何更多,锁将成功。

When I ran into this problem, the best solution I came up with was to continually try to get an exclusive lock on the file; while the file is being written, the locking attempt will fail, essentially the method in this answer. Once the file isn't being written to any more, the lock will succeed.

不幸的是,这样做的唯一的办法就是换一个try / catch围绕打开文件,这使我畏缩 - 不得不使用try / catch语句总是痛苦的。这里似乎并不被周围的任何方式,虽然如此,这是我结束了使用。

Unfortunately, the only way to do that is to wrap a try/catch around opening the file, which makes me cringe - having to use try/catch is always painful. There just doesn't seem to be any way around that, though, so it's what I ended up using.

在这个问题的答案修改code的伎俩,所以我结束了使用这样的:

Modifying the code in that answer does the trick, so I ended up using something like this:

private void WaitForFile(FileInfo file)
{
    FileStream stream = null;
    bool FileReady = false;
    while(!FileReady)
    {
        try
        {
            using(stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None)) 
            { 
                FileReady = true; 
            }
        }
        catch (IOException)
        {
            //File isn't ready yet, so we need to keep on waiting until it is.
        }
        //We'll want to wait a bit between polls, if the file isn't ready.
        if(!FileReady) Thread.Sleep(1000);
    }
}

这篇关于FileSystemWatcher的 - 是文件准备好使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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