273

Is there any way to check whether a file is locked without using a try/catch block?

Right now, the only way I know of is to just open the file and catch any System.IO.IOException.

Hossein Narimani Rad
32.7k19 gold badges92 silver badges121 bronze badges
asked Aug 4, 2008 at 14:56
3
  • 13
    The trouble is that an IOException could be thrown for many reasons other than a locked file. Commented Feb 9, 2010 at 16:48
  • 5
    This is an old question, and all of the old answers are incomplete or wrong. I added a complete and correct answer. Commented Dec 23, 2013 at 18:27
  • 1
    I know this is not quite the answer to the question as is, but some subset of developers who are looking at this for help might have this option: If you start the process that owns the lock with System.Diagnostics.Process you can .WaitForExit(). Commented Feb 2, 2016 at 17:44

12 Answers 12

190

When I faced with a similar problem, I finished with the following code:

public class FileManager
{
 private string _fileName;
 private int _numberOfTries;
 private int _timeIntervalBetweenTries;
 private FileStream GetStream(FileAccess fileAccess)
 {
 var tries = 0;
 while (true)
 {
 try
 {
 return File.Open(_fileName, FileMode.Open, fileAccess, Fileshare.None); 
 }
 catch (IOException e)
 {
 if (!IsFileLocked(e))
 throw;
 if (++tries > _numberOfTries)
 throw new MyCustomException("The file is locked too long: " + e.Message, e);
 Thread.Sleep(_timeIntervalBetweenTries);
 }
 }
 }
 private static bool IsFileLocked(IOException exception)
 {
 int errorCode = Marshal.GetHRForException(exception) & ((1 << 16) - 1);
 return errorCode == 32 || errorCode == 33;
 }
 // other code
}
davidsbro
2,7684 gold badges27 silver badges36 bronze badges
answered Jul 8, 2010 at 9:12

10 Comments

@kite: There is a better way now stackoverflow.com/a/20623302/141172
What if between return false and your attempt to open the file again something else snatches it up? Race conditions ahoy!
@RenniePet The following page should be more helpful: msdn.microsoft.com/en-us/library/windows/desktop/… The relevant errors are ERROR_SHARING_VIOLATION and ERROR_LOCK_VIOLATION
What's the purpose of bit-masking here, if you compare the result to a constant? Also, GetHRForException has side effects, HResult can be read directly since .NET 4.5.
@BartoszKP Exactly, and thank you. Here's the updated contents of the 'catch' clause: const int ERROR_SHARING_VIOLATION = 0x20; const int ERROR_LOCK_VIOLATION = 0x21; int errorCode = e.HResult & 0x0000FFFF; return errorCode == ERROR_SHARING_VIOLATION || errorCode == ERROR_LOCK_VIOLATION;
|
167

The other answers rely on old information. This one provides a better solution.

Long ago it was impossible to reliably get the list of processes locking a file because Windows simply did not track that information. To support the Restart Manager API, that information is now tracked. The Restart Manager API is available beginning with Windows Vista and Windows Server 2008 (Restart Manager: Run-time Requirements).

I put together code that takes the path of a file and returns a List<Process> of all processes that are locking that file.

static public class FileUtil
{
 [StructLayout(LayoutKind.Sequential)]
 struct RM_UNIQUE_PROCESS
 {
 public int dwProcessId;
 public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime;
 }
 const int RmRebootReasonNone = 0;
 const int CCH_RM_MAX_APP_NAME = 255;
 const int CCH_RM_MAX_SVC_NAME = 63;
 enum RM_APP_TYPE
 {
 RmUnknownApp = 0,
 RmMainWindow = 1,
 RmOtherWindow = 2,
 RmService = 3,
 RmExplorer = 4,
 RmConsole = 5,
 RmCritical = 1000
 }
 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
 struct RM_PROCESS_INFO
 {
 public RM_UNIQUE_PROCESS Process;
 [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_APP_NAME + 1)]
 public string strAppName;
 [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_SVC_NAME + 1)]
 public string strServiceShortName;
 public RM_APP_TYPE ApplicationType;
 public uint AppStatus;
 public uint TSSessionId;
 [MarshalAs(UnmanagedType.Bool)]
 public bool bRestartable;
 }
 [DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
 static extern int RmRegisterResources(uint pSessionHandle,
 UInt32 nFiles,
 string[] rgsFilenames,
 UInt32 nApplications,
 [In] RM_UNIQUE_PROCESS[] rgApplications,
 UInt32 nServices,
 string[] rgsServiceNames);
 [DllImport("rstrtmgr.dll", CharSet = CharSet.Auto)]
 static extern int RmStartSession(out uint pSessionHandle, int dwSessionFlags, string strSessionKey);
 [DllImport("rstrtmgr.dll")]
 static extern int RmEndSession(uint pSessionHandle);
 [DllImport("rstrtmgr.dll")]
 static extern int RmGetList(uint dwSessionHandle,
 out uint pnProcInfoNeeded,
 ref uint pnProcInfo,
 [In, Out] RM_PROCESS_INFO[] rgAffectedApps,
 ref uint lpdwRebootReasons);
 /// <summary>
 /// Find out what process(es) have a lock on the specified file.
 /// </summary>
 /// <param name="path">Path of the file.</param>
 /// <returns>Processes locking the file</returns>
 /// <remarks>See also:
 /// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373661(v=vs.85).aspx
 /// http://wyupdate.googlecode.com/svn-history/r401/trunk/frmFilesInUse.cs (no copyright in code at time of viewing)
 /// 
 /// </remarks>
 static public List<Process> WhoIsLocking(string path)
 {
 uint handle;
 string key = Guid.NewGuid().ToString();
 List<Process> processes = new List<Process>();
 int res = RmStartSession(out handle, 0, key);
 if (res != 0)
 throw new Exception("Could not begin restart session. Unable to determine file locker.");
 try
 {
 const int ERROR_MORE_DATA = 234;
 uint pnProcInfoNeeded = 0,
 pnProcInfo = 0,
 lpdwRebootReasons = RmRebootReasonNone;
 string[] resources = new string[] { path }; // Just checking on one resource.
 res = RmRegisterResources(handle, (uint)resources.Length, resources, 0, null, 0, null);
 if (res != 0) 
 throw new Exception("Could not register resource."); 
 //Note: there's a race condition here -- the first call to RmGetList() returns
 // the total number of process. However, when we call RmGetList() again to get
 // the actual processes this number may have increased.
 res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons);
 if (res == ERROR_MORE_DATA)
 {
 // Create an array to store the process results
 RM_PROCESS_INFO[] processInfo = new RM_PROCESS_INFO[pnProcInfoNeeded];
 pnProcInfo = pnProcInfoNeeded;
 // Get the list
 res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);
 if (res == 0)
 {
 processes = new List<Process>((int)pnProcInfo);
 // Enumerate all of the results and add them to the 
 // list to be returned
 for (int i = 0; i < pnProcInfo; i++)
 {
 try
 {
 processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId));
 }
 // catch the error -- in case the process is no longer running
 catch (ArgumentException) { }
 }
 }
 else
 throw new Exception("Could not list processes locking resource."); 
 }
 else if (res != 0)
 throw new Exception("Could not list processes locking resource. Failed to get size of result."); 
 }
 finally
 {
 RmEndSession(handle);
 }
 return processes;
 }
}

UPDATE

Here is another discussion with sample code on how to use the Restart Manager API.

Walkman
1191 gold badge3 silver badges12 bronze badges
answered Dec 16, 2013 at 23:47

21 Comments

The only answer here that actually answers the OP question... nice!
Will this work if the file is located on a network share and the file is possibly locked on another pc?
I just used this and it does work across the network.
If anyone is interested, I created a gist inspired by this answer but simpler and improved with the properly formatted documentation from msdn. I also drew inspiration from Raymond Chen's article and took care of the race condition. BTW I noticed that this method takes about 30ms to run (with the RmGetList method alone taking 20ms), while the DixonD's method, trying to acquire a lock, takes less than 5ms... Keep that in mind if you plan to use it in a tight loop...
@VadimLevkovsky oh sorry, here is a working link: gist.github.com/mlaily/9423f1855bb176d52a327f5874915a97
|
132

No, unfortunately, and if you think about it, that information would be worthless anyway since the file could become locked the very next second (read: short timespan).

Why specifically do you need to know if the file is locked anyway? Knowing that might give us some other way of giving you good advice.

If your code would look like this:

if not locked then
 open and update file

Then between the two lines, another process could easily lock the file, giving you the same problem you were trying to avoid to begin with: exceptions.

answered Aug 4, 2008 at 14:59

11 Comments

If file is locked, we can wait some time and try again. If it is another kind of issue with file access then we should just propagate exception.
Yes, but the standalone check for whether a file is locked is useless, the only correct way to do this is to try to open the file for the purpose you need the file, and then handle the lock problem at that point. And then, as you say, wait, or deal with it in another way.
You could argue the same for access rights though it would of course be more unlikely.
@LasseV.Karlsen Another benefit of doing a preemptive check is that you can notify the user before attempting a possible long operation and interrupting mid-way. The lock occurring mid-way is still possible of course and needs to be handled, but in many scenarios this would help the user experience considerably.
There are plenty of situations in which a lock test would not be "useless". Checking IIS logs, which locks one file for writing daily, to see which is locked is a representative example of a whole class of logging situations like this. It's possible to identify a system context well enough to get value from a lock test. "✗ DO NOT use exceptions for the normal flow of control, if possible."learn.microsoft.com/en-us/dotnet/standard/design-guidelines/…
|
16

You can also check if any process is using this file and show a list of programs you must close to continue like an installer does.

public static string GetFileProcessName(string filePath)
{
 Process[] procs = Process.GetProcesses();
 string fileName = Path.GetFileName(filePath);
 foreach (Process proc in procs)
 {
 if (proc.MainWindowHandle != new IntPtr(0) && !proc.HasExited)
 {
 ProcessModule[] arr = new ProcessModule[proc.Modules.Count];
 foreach (ProcessModule pm in proc.Modules)
 {
 if (pm.ModuleName == fileName)
 return proc.ProcessName;
 }
 }
 }
 return null;
}
Markus Safar
6,6205 gold badges33 silver badges46 bronze badges
answered Apr 1, 2011 at 11:19

1 Comment

This can only tell which process keeps an executable module (dll) locked. It will not tell you which process has locked, say, your xml file.
14

Instead of using interop you can use the .NET FileStream class methods Lock and Unlock:

FileStream.Lock http://msdn.microsoft.com/en-us/library/system.io.filestream.lock.aspx

FileStream.Unlock http://msdn.microsoft.com/en-us/library/system.io.filestream.unlock.aspx

answered Mar 8, 2010 at 17:09

3 Comments

This is really the correct answer, as it gives the user the ability to not just lock/unlock files but sections of the files as well. All of the "You can't do that without transactions" comments may raise a valid concern, but are not useful since they're pretending that the functionality isn't there or is somehow hidden when it's not.
Actually, this is not a solution because you cannot create an instance of FileStream if the file is locked. (an exception will be thrown)
I would argue it is a solution. If your goal is to simply check for a file lock. an exception being thrown gives you preciesly the answer you are looking for.
9

A variation of DixonD's excellent answer (above).

public static bool TryOpen(string path,
 FileMode fileMode,
 FileAccess fileAccess,
 FileShare fileShare,
 TimeSpan timeout,
 out Stream stream)
{
 var endTime = DateTime.Now + timeout;
 while (DateTime.Now < endTime)
 {
 if (TryOpen(path, fileMode, fileAccess, fileShare, out stream))
 return true;
 }
 stream = null;
 return false;
}
public static bool TryOpen(string path,
 FileMode fileMode,
 FileAccess fileAccess,
 FileShare fileShare,
 out Stream stream)
{
 try
 {
 stream = File.Open(path, fileMode, fileAccess, fileShare);
 return true;
 }
 catch (IOException e)
 {
 if (!FileIsLocked(e))
 throw;
 stream = null;
 return false;
 }
}
private const uint HRFileLocked = 0x80070020;
private const uint HRPortionOfFileLocked = 0x80070021;
private static bool FileIsLocked(IOException ioException)
{
 var errorCode = (uint)Marshal.GetHRForException(ioException);
 return errorCode == HRFileLocked || errorCode == HRPortionOfFileLocked;
}

Usage:

private void Sample(string filePath)
{
 Stream stream = null;
 try
 {
 var timeOut = TimeSpan.FromSeconds(1);
 if (!TryOpen(filePath,
 FileMode.Open,
 FileAccess.ReadWrite,
 FileShare.ReadWrite,
 timeOut,
 out stream))
 return;
 // Use stream...
 }
 finally
 {
 if (stream != null)
 stream.Close();
 }
}
Markus Safar
6,6205 gold badges33 silver badges46 bronze badges
answered Jan 3, 2013 at 3:41

8 Comments

This is the only practical solution so far. And it works.
Boooyyyyy... You better put some Thread.Sleep(200) in there and get off my CPU!
What part do you want to sleep? Why?
@Tristan I guess, Paul Knopf meant to use Thread.Sleep between access tries.
Try reading @PaulKnopf's comment without using an irate girlfriends voice in your head.
|
7

Here's a variation of DixonD's code that adds number of seconds to wait for file to unlock, and try again:

public bool IsFileLocked(string filePath, int secondsToWait)
{
 bool isLocked = true;
 int i = 0;
 while (isLocked && ((i < secondsToWait) || (secondsToWait == 0)))
 {
 try
 {
 using (File.Open(filePath, FileMode.Open)) { }
 return false;
 }
 catch (IOException e)
 {
 var errorCode = Marshal.GetHRForException(e) & ((1 << 16) - 1);
 isLocked = errorCode == 32 || errorCode == 33;
 i++;
 if (secondsToWait !=0)
 new System.Threading.ManualResetEvent(false).WaitOne(1000);
 }
 }
 return isLocked;
}
if (!IsFileLocked(file, 10))
{
 ...
}
else
{
 throw new Exception(...);
}
Markus Safar
6,6205 gold badges33 silver badges46 bronze badges
answered Sep 24, 2013 at 18:34

1 Comment

Well, I was doing a kind of the same thing in my original answer till somebody decided to simplify it:) stackoverflow.com/posts/3202085/revisions
5

You could call LockFile via interop on the region of file you are interested in. This will not throw an exception, if it succeeds you will have a lock on that portion of the file (which is held by your process), that lock will be held until you call UnlockFile or your process dies.

answered Jul 24, 2009 at 6:42

Comments

4

Then between the two lines, another process could easily lock the file, giving you the same problem you were trying to avoid to begin with: exceptions.

However, this way, you would know that the problem is temporary, and to retry later. (E.g., you could write a thread that, if encountering a lock while trying to write, keeps retrying until the lock is gone.)

The IOException, on the other hand, is not by itself specific enough that locking is the cause of the IO failure. There could be reasons that aren't temporary.

answered Aug 17, 2008 at 18:17

Comments

4

You can see if the file is locked by trying to read or lock it yourself first.

Please see my answer here for more information.

answered Mar 9, 2009 at 12:54

Comments

0

Same thing but in Powershell

function Test-FileOpen
{
 Param
 ([string]$FileToOpen)
 try
 {
 $openFile =([system.io.file]::Open($FileToOpen,[system.io.filemode]::Open))
 $open =$true
 $openFile.close()
 }
 catch
 {
 $open = $false
 }
 $open
}
Markus Safar
6,6205 gold badges33 silver badges46 bronze badges
answered Dec 23, 2015 at 14:24

Comments

-1

What I ended up doing is:

internal void LoadExternalData() {
 FileStream file;
 if (TryOpenRead("filepath/filename", 5, out file)) {
 using (file)
 using (StreamReader reader = new StreamReader(file)) {
 // do something 
 }
 }
}
internal bool TryOpenRead(string path, int timeout, out FileStream file) {
 bool isLocked = true;
 bool condition = true;
 do {
 try {
 file = File.OpenRead(path);
 return true;
 }
 catch (IOException e) {
 var errorCode = Marshal.GetHRForException(e) & ((1 << 16) - 1);
 isLocked = errorCode == 32 || errorCode == 33;
 condition = (isLocked && timeout > 0);
 if (condition) {
 // we only wait if the file is locked. If the exception is of any other type, there's no point on keep trying. just return false and null;
 timeout--;
 new System.Threading.ManualResetEvent(false).WaitOne(1000);
 }
 }
 }
 while (condition);
 file = null;
 return false;
}
Markus Safar
6,6205 gold badges33 silver badges46 bronze badges
answered Dec 16, 2013 at 19:19

2 Comments

You should consider a Using block for file
Use System.Threading.Thread.Sleep(1000) instead of new System.Threading.ManualResetEvent(false).WaitOne(1000)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.