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


Question

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
            }
1
17
1/8/2009 4:05:34 PM

Accepted Answer

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.

24
1/8/2009 4:08:46 PM

The truth is, even if you do figure out a way to check if the file is "locked" by the time you get to the next line where you open the file, something else in the OS may try to get a hold of that file, and your code to open it will fail anyway. You'll have to put a try/catch there anyway. Therefore, I say no. There isn't really a better solution.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon