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

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

问题描述

我正在用 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 进行检查.

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.

原件:过去几年我一直在使用这个代码,我没有遇到任何问题.

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)
{
    try
    {
        using(FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None))
        {
            stream.Close();
        }
    }
    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;
    }

    //file is not locked
    return false;
}

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

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