How to Check if a Process has a Lock on a File

File locks caused by open processes are a common source of error when trying to perform I/O operations on a file. This example illustrates an efficient way to check for file locks using a simple extension method. 
 
Step 1:  Create an extension method on the FileInfo class:
  1. public static bool IsLocked(this FileInfo f)  
  2. {  
  3.     try  
  4.     {  
  5.         string fpath = f.FullName;  
  6.         FileStream fs = File.OpenWrite(fpath);  
  7.         fs.Close();  
  8.         return false;  
  9.     }  
  10.  
  11.     catch (Exception) return true}    
  12. }  
Step 2:  Create a reference to the file and check it before performing your operation: 
  1. FileInfo fi = new FileInfo(@"C:\4067918.TIF");    
  2. if (!fi.IsLocked()//DO SOMETHING HERE ;}