[ACCEPTED]-Detecting whether a file is locked by another process (or indeed the same process)-.net

Accepted answer
Score: 26

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

Score: 5

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

Score: 1

No that I am aware of, there is no call 5 to check if the file is in use - you have 4 to try to open it and handle the exception 3 as you are doing. Another problem is that 2 it is hard to distinguish between in use 1 and no access allowed.

Score: 1

To answer your question, it would be more 4 efficient to write the following extension 3 method for the FileInfo class:

      public static bool IsLocked(this FileInfo f)
    {
            try 
            {
                string fpath = f.FullName;
                FileStream fs = File.OpenWrite(fpath);
                fs.Close();        
                return false;
            }

            catch (Exception) { return true; }      
    }

Once you have 2 created the method, you can do a quick check 1 like this:

  FileInfo fi = new FileInfo(@"C:\4067918.TIF");
  if (!fi.IsLocked()) { //DO SOMETHING HERE; }

More Related questions