有没有一种方法来检查文件是否在使用? [英] Is there a way to check if a file is in use?

查看:227
本文介绍了有没有一种方法来检查文件是否在使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写在C#程序需要重复访问1图像文件。大部分的工作时间,但如果我的电脑的运行速度快,它会尝试访问该文件之前,它被保存回文件系统并抛出一个错误:文件被另一个进程使用的。

I'm writing a program in C# that needs to repeatedly access 1 image file. Most of the time it works, but if my computer's running fast, it will try to access the file before it's been saved back to the filesystem and throw an error: "File in use by another process".

我想找到解决的办法,但我所有的谷歌搜索只取得了通过使用异常处理创建检查。这是对我的宗教,所以我想知道如果任何人有这样做的更好的办法?

I would like to find a way around this, but all my Googling has only yielded creating checks by using exception handling. This is against my religion, so I was wondering if anyone has a better way of doing it?

推荐答案

更新这个解决方案注意:用 FileAccess.ReadWrite 检查将失败为只读文件,因此该解决方案已被修改为检查与 FileAccess.Read 。虽然这种解决方案的工作,因为试图检查与 FileAccess.Read 如果文件有写或阅读它锁会失败,但是,这种解决方案将无法工作,如果没有按文件T有它写或读锁,也就是说,它已被打开(读或写)与FileShare.Read或FileShare.Write访问。

Updated NOTE on this solution: Checking with FileAccess.ReadWrite will fail for Read-Only files so the solution has been modified to check with FileAccess.Read. While this solution works because trying to check with FileAccess.Read will fail if the file has a Write or Read lock on it, however, this solution will not work if the file doesn't have a Write or Read lock on it, i.e. it has been opened (for reading or writing) with FileShare.Read or FileShare.Write access.

原文:
我用这个code在过去的几年中,我还没有与它有任何问题。

ORIGINAL: I've used this code for the past several years, and I haven't had any issues with it.

了解您使用异常犹豫,但你不能避免他们所有的时间:

Understand your hesitation about using exceptions, but you can't avoid them all of the time:

protected virtual bool IsFileLocked(FileInfo file)
{
    FileStream stream = null;

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None);
    }
    catch (IOException)
    {
        //the file is unavailable because it is:
        //still being written to
        //or being processed by another thread
        //or does not exist (has already been processed)
        return true;
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }

    //file is not locked
    return false;
}

这篇关于有没有一种方法来检查文件是否在使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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