Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting whether a file is locked by another process (or indeed the same process) [duplicate]

Tags:

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
            }
like image 875
Jack Hughes Avatar asked Jan 08 '09 16:01

Jack Hughes


1 Answers

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.

like image 138
Sunny Milenov Avatar answered Sep 19 '22 19:09

Sunny Milenov