268

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
  • 31,361
  • 18
  • 86
  • 116
ricree
  • 35,626
  • 13
  • 36
  • 27
  • 12
    The trouble is that an IOException could be thrown for many reasons other than a locked file. – JohnFx Feb 09 '10 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. – Eric J. Dec 23 '13 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(). – amalgamate Feb 02 '16 at 17:44

12 Answers12

187

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,761
  • 4
  • 23
  • 33
DixonD
  • 6,557
  • 5
  • 31
  • 52
  • too bad opening sqlite db used by firefox will leave program hang waiting for just the exception to be thrown – kite Sep 12 '13 at 06:18
  • 2
    @kite: There is a better way now http://stackoverflow.com/a/20623302/141172 – Eric J. Jan 22 '14 at 22:48
  • 4
    What if between `return false` and your attempt to open the file again something else snatches it up? Race conditions ahoy! – jocull Apr 01 '14 at 20:17
  • What do the other HRESULTS that can come back from this mean? How did you know that 32 and 33 represent types of locking? – Daniel Revell Jan 15 '15 at 14:37
  • 1
    @DanRevell Check this: http://msdn.microsoft.com/library/windows/desktop/aa378137.aspx – DixonD Jan 15 '15 at 18:06
  • Maybe Microsoft has changed that web page, but it currently doesn't include error codes ending with 32 or 33. – RenniePet Jun 08 '16 at 13:50
  • 2
    @RenniePet The following page should be more helpful: https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382%28v=vs.85%29.aspx The relevant errors are ERROR_SHARING_VIOLATION and ERROR_LOCK_VIOLATION – DixonD Jun 08 '16 at 17:49
  • 2
    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 Apr 18 '17 at 16:51
  • 2
    @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;` – taiji123 Jul 15 '19 at 14:40
  • This method works but sometimes gets hung up and takes a minute or more to finish. – Erik Schroder Dec 16 '22 at 17:18
163

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.

Markus Safar
  • 6,324
  • 5
  • 28
  • 44
Eric J.
  • 147,927
  • 63
  • 340
  • 553
  • 17
    The only answer here that actually answers the OP question... nice! – Serj Sagan Dec 23 '13 at 15:14
  • 6
    Will this work if the file is located on a network share and the file is possibly locked on another pc? – Coder14 Dec 09 '14 at 15:52
  • @Lander: The documentation does not say, and I have not tried it. If you can, setup a test and see if it works. Feel free to update my answer with your findings. – Eric J. Dec 09 '14 at 20:11
  • 8
    I just used this and it does work across the network. – Jonathan D Feb 19 '15 at 11:03
  • Code looks taken from [here](https://msdn.microsoft.com/en-us/magazine/cc163450.aspx), it contains some flaws and should be improved with [The Old New Thing](http://blogs.msdn.com/b/oldnewthing/archive/2012/02/17/10268840.aspx) – SerG Apr 20 '15 at 13:36
  • @SerG: Thank you for pointing out that link. As you have already sorted out what (some of) the improvements should be, feel free to just edit my original post. – Eric J. Apr 20 '15 at 17:39
  • @SerG Did (either of) you update the answer? Both the links appear to be outdated. – Tormod Jan 08 '16 at 08:37
  • 1
    @Tormod: The sample code in my answer has not been updated. SerG didn't say specifically what he thought the improvements are and I have not had time to dig in. I added an updated link for his now-dead link to the question. Here it is again for reference https://blogs.msdn.microsoft.com/oldnewthing/20120217-00/?p=8283 – Eric J. Jan 08 '16 at 18:10
  • 1
    @Tormod I also had not had time to edit the answer reliably correct. But to the best of my memory Raymond Chen in the article describes all in details. – SerG Jan 11 '16 at 09:52
  • 5
    If anyone is interested, [I created a gist](https://gist.github.com/yaurthek/9423f1855bb176d52a327f5874915a97) 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... – Melvyn May 12 '16 at 09:09
  • Is there a VS2005 solution please? – Fandango68 Apr 21 '17 at 02:01
  • 1
    @Fernando68: This has nothing to do with your version of Visual Studio. The code must run on Windows Vista or later, or Windows Server 2008 or later. Older versions of Windows don't offer the Restart Manager (but you can still use the other, less optimal answers on those older Windows versions). – Eric J. Apr 21 '17 at 17:17
  • @Yaurthek sorry, but your gist link seems to be broken or outdated – Vadim Levkovsky Aug 16 '17 at 09:06
  • 5
    @VadimLevkovsky oh sorry, here is a working link: https://gist.github.com/mlaily/9423f1855bb176d52a327f5874915a97 – Melvyn Aug 16 '17 at 09:39
  • Is this thread-safe? Can two processes use this approach simultaneously, or does it have to be some kind of orchestrated singleton? Are network locks only identified if the locking process is local, or will remote process locks be detected as well? – brianary May 25 '18 at 16:40
  • The RestartManager is a Windows API and should be safe for concurrent use (though the docs don't explicitly state that). The C# wrapper code I provide should be thread safe. – Eric J. Jun 01 '18 at 17:26
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.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
  • 16
    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. – DixonD Oct 08 '10 at 05:11
  • 14
    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. – Lasse V. Karlsen Oct 08 '10 at 08:06
  • 2
    You could argue the same for access rights though it would of course be more unlikely. – ctusch Jun 06 '13 at 09:38
  • 8
    @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. – Thiru Jun 19 '13 at 18:01
  • 1
    I think the best to do is a File.ReadWaitForUnlock(file, timeout) method. and returns null or the FileStream depending on success. I'm following the logic right here? – Bart Calixto Dec 13 '13 at 20:50
  • @Bart Please elaborate, where is that method defined, can you provide a link to it? And please note that my answer was posted 3rd quarter 2008, different .NET runtime and all, but still.... What is `File.ReadWaitForUnlock`? – Lasse V. Karlsen Dec 13 '13 at 21:52
  • @LasseV.Karlsen checkout my answer for what I ended up using based on your answer. ReadWaitForUnlock is my own method, changed to TryOpenRead at the end. – Bart Calixto Dec 16 '13 at 19:20
  • It is now possible to get the process that is locking a file. See http://stackoverflow.com/a/20623302/141172 – Eric J. Jan 15 '14 at 07:56
  • 3
    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."_ — https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/exception-throwing – brianary May 25 '18 at 16:37
  • I don't know why your answer was the one accepted but your reasoning is just wrong. There are several legitimate uses to check for a file being locked by another process. You are considering that you will check in advance, but you can also check if the file is locked *after* an unsuccessful attempt to read from/write to the file, so you can properly log and/or inform the user. – Alexandre M Feb 07 '19 at 03:26
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,324
  • 5
  • 28
  • 44
Aralmo
  • 177
  • 1
  • 2
  • 16
    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. – Constantin Jul 08 '12 at 20:58
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

Sergio Vicente
  • 980
  • 1
  • 10
  • 18
  • 1
    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. – BrainSlugs83 Oct 13 '11 at 21:49
  • 35
    Actually, this is not a solution because you cannot create an instance of FileStream if the file is locked. (an exception will be thrown) – Zé Carlos Jan 27 '12 at 17:54
  • 1
    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. – Alexander Høst Mar 04 '22 at 19:08
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,324
  • 5
  • 28
  • 44
Tristan
  • 1,466
  • 1
  • 16
  • 24
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,324
  • 5
  • 28
  • 44
live-love
  • 48,840
  • 22
  • 240
  • 204
  • 1
    Well, I was doing a kind of the same thing in my original answer till somebody decided to simplify it:) http://stackoverflow.com/posts/3202085/revisions – DixonD Jan 10 '14 at 11:25
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.

Sam Saffron
  • 128,308
  • 78
  • 326
  • 506
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.

Sören Kuklau
  • 19,454
  • 7
  • 52
  • 86
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.

Community
  • 1
  • 1
Brian R. Bondy
  • 339,232
  • 124
  • 596
  • 636
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,324
  • 5
  • 28
  • 44
Thom Schumacher
  • 1,469
  • 13
  • 24
-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,324
  • 5
  • 28
  • 44
Bart Calixto
  • 19,210
  • 11
  • 78
  • 114