检测是否一个​​文件被其他进程锁定(或实际上相同的过程) [英] Detecting whether a file is locked by another process (or indeed the same process)

查看:157
本文介绍了检测是否一个​​文件被其他进程锁定(或实际上相同的过程)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我如何做到这一点的时刻。我尝试打开与文件共享设置为无文件。所以我想独占accesss到文件中。如果我不能拿到那么它的一个不错的选择别人已经锁定该文件。

我们有了一个更好的,更快的方式。任何想法?

 尝试
            {
                使用(的FileStream FS = File.open方法(GetLockFilename(),FileMode.Open,FileAccess.ReadWrite,FileShare.None))
                {
                    fs.Close();
                }
                //该文件没有锁定
            }
            赶上(例外)
            {
                //该文件被锁定
            }
 

解决方案

无需首先检查文件是否被锁定,然后访问它,检查和接入之间的一些其他进程可能仍然获得了锁文件。所以,你做的是正确的,如果你成功了,对文件做你的工作。

This is how I do it at the moment. I try to open the file with the FileShare set to none. So I want exclusive accesss to the file. If I can't get that then its a good bet somebody else has the file locked.

There's got to be a better and faster way. Any ideas?

            try
            {
                using (FileStream fs = File.Open(GetLockFilename(), FileMode.Open, FileAccess.ReadWrite, FileShare.None))
                {
                    fs.Close();
                }
                // The file is not locked
            }
            catch (Exception)
            {
                // The file is locked
            }

解决方案

There is no need first to check if the file is locked and then access it, as between the check and the access some other process may still get a lock on the file. So, what you do is correct, if you succeed, do your work with the file.

这篇关于检测是否一个​​文件被其他进程锁定(或实际上相同的过程)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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