如何检查文件是否在使用? [英] How to check if a file is in use?

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

问题描述

有没有什么办法来第一次测试,如果一个文件正在使用中试图打开阅读过吗?例如,code此块会,如果该文件仍然被写入或者被认为是在使用中抛出一个异常:

Is there any way to first test if a file is in use before attempting to open it for reading? For example, this block of code will throw an exception if the file is still being written to or is considered in use:

try
{
    FileStream stream = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read);
}
catch (IOException ex)
{
    // ex.Message == "The process cannot access the file 'XYZ' because it is being used by another process."
}

我看着周围,最好的我能找到的是进行某种形式的投票里面一试捕的,那种感觉的这样的哈克。我希望那里是东西 System.IO.FileInfo ,但没有。

I've looked all around and the best I can find is to perform some sort of polling with a try catch inside, and that feels so hacky. I would expect there to be something on System.IO.FileInfo but there isn't.

这是一个更好的办法的任何想法?

Any ideas on a better way?

推荐答案

你可以通过在P调用锁文件API函数/直接调用层。你会使用由上的FileStream的SafeFileHandle属性返回的句柄。 调用API直接将允许你检查返回值,而不是诉诸捕获异常错误条件。

"You can call the LockFile API function through the P/Invoke layer directly. You would use the handle returned by the SafeFileHandle property on the FileStream. Calling the API directly will allow you to check the return value for an error condition as opposed to resorting to catching an exception."

的try / catch块是正确的解决办法(虽然你想捕获IOException异常,并非所有的例外)。有没有办法可以正确同步,因为测试锁+获取锁不是一个原子操作。

"The try/catch block is the CORRECT solution (though you want to catch IOException, not all exceptions). There's no way you can properly synchronize, because testing the lock + acquiring the lock is not an atomic operation."

请记住,文件系统是挥发性的:仅仅因为你的文件是在一个国家的一个操作并不意味着它会在相同状态下一个操作您必须能够处理从文件系统的异常。

"Remember, the file system is volatile: just because your file is in one state for one operation doesn't mean it will be in the same state for the next operation. You have to be able to handle exceptions from the file system."

<一个href="http://stackoverflow.com/questions/698442/using-c-is-it-possible-to-test-if-a-lock-is-held-on-a-file">http://stackoverflow.com/questions/698442/using-c-is-it-possible-to-test-if-a-lock-is-held-on-a-file

http://www.dotnet247.com/247reference/msgs/32/ 162678.aspx

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

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