检测是否一个​​文件被其他进程锁定(或实际上相同的过程)进程、过程、文件

2023-09-02 10:49:17 作者:醉态萌生^@^

这是我如何做到这一点的时刻。我尝试打开与文件共享设置为无文件。所以我想独占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.