我应该如何检查“动态”文件可访问性(例如,在使用中) [英] How should I check "dynamic" file accessibility (e.g., in use)

查看:87
本文介绍了我应该如何检查“动态”文件可访问性(例如,在使用中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该如何检查是否可以为Read打开文件,包括该文件在另一个进程中正在使用的情况?

我可以捕获 IOException 我得到的地方:

进程无法访问文件'C:\ ...',因为它正由另一个进程使用。

但我宁愿提前检查读取能力,并控制错误信息。

(我知道这会在检查和文件打开之间留下一个机会之窗,但在这种情况下该文件的性质是用户可能已手动打开它,因此预检应该捕获大多数的情况,捕获异常将处理其余的。)

建议?



How should I check if a file can be opened for Read, including cases like the file is in use in another process?
I can catch the IOException where I get:
"The process cannot access the file 'C:\...' because it is being used by another process."
but I'd rather check for Read-ability in advance, and control the error message.
(I know this leaves a "window of opportunity" between the checking and the file opening, but in this case the nature of the file is that the user may have opened it manually, so pre-checking should catch most cases, and catching the exception will handle the rest.)
Suggestions?

推荐答案

我发现这篇文章:



检查文件是否正在使用通过另一个流程 [ ^ ]
I found this article:

Check if file is being used by another process[^]


我会创建一个类似这样的函数:



I would create a function something like this:

public static bool TryOpenRead(this System.IO.FileInfo file, out System.IO.FileStream fileStream)
{
    fileStream = null;

    try
    {
        fileStream = file.OpenRead();

        return true;
    }
    catch (System.IO.IOException ioException)
    {

    }

    return false;
}





当然,这是文件信息 [ ^ ]。



这至少是唯一可靠的方法,既可以查看文件是否可以读取并同时获取文件。



Which, of course, is an extension method for FileInfo[^].

Thats at least the only reliable way to both see if the file is available for reading AND get the file at the same time.


这篇关于我应该如何检查“动态”文件可访问性(例如,在使用中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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