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:
- 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; }
- }
Step 2: Create a reference to the file and check it before performing your operation:
- FileInfo fi = new FileInfo(@"C:\4067918.TIF");
- if (!fi.IsLocked()) { }