How to check for file lock? [duplicate]
Asked Answered
A

12

270

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.

Adamite answered 4/8, 2008 at 14:56 Comment(3)
The trouble is that an IOException could be thrown for many reasons other than a locked file.Scyphus
This is an old question, and all of the old answers are incomplete or wrong. I added a complete and correct answer.Paulson
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().Autarch
I
133

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.

Inhabiter answered 4/8, 2008 at 14:59 Comment(11)
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.Puttergill
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.Inhabiter
You could argue the same for access rights though it would of course be more unlikely.Jeseniajesh
@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.Tlaxcala
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?Pneumatic
@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?Inhabiter
@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.Pneumatic
It is now possible to get the process that is locking a file. See https://mcmap.net/q/54424/-how-to-check-for-file-lock-duplicatePaulson
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/…Syndic
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.Anastassia
If you're dealing with multiple files, checking if any are locked before updating helps keep things more atomicTweeddale
P
188

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

}
Puttergill answered 8/7, 2010 at 9:12 Comment(10)
too bad opening sqlite db used by firefox will leave program hang waiting for just the exception to be thrownBipartisan
@kite: There is a better way now https://mcmap.net/q/54424/-how-to-check-for-file-lock-duplicatePaulson
What if between return false and your attempt to open the file again something else snatches it up? Race conditions ahoy!Fictitious
What do the other HRESULTS that can come back from this mean? How did you know that 32 and 33 represent types of locking?Cymar
@DanRevell Check this: msdn.microsoft.com/library/windows/desktop/aa378137.aspxPuttergill
Maybe Microsoft has changed that web page, but it currently doesn't include error codes ending with 32 or 33.Jeth
@Jeth 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_VIOLATIONPuttergill
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.Mischance
@Mischance 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;Epistasis
This method works but sometimes gets hung up and takes a minute or more to finish.Gilly
P
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.

Paulson answered 16/12, 2013 at 23:47 Comment(21)
The only answer here that actually answers the OP question... nice!Smitherman
Will this work if the file is located on a network share and the file is possibly locked on another pc?Rundlet
@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.Paulson
I just used this and it does work across the network.Greenfinch
Code looks taken from here, it contains some flaws and should be improved with The Old New ThingHeliotropism
@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.Paulson
@Heliotropism Did (either of) you update the answer? Both the links appear to be outdated.Heterolysis
@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 blogs.msdn.microsoft.com/oldnewthing/20120217-00/?p=8283Paulson
@Heterolysis 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.Heliotropism
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...Hygroscope
Is there a VS2005 solution please?Deface
@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).Paulson
@Yaurthek sorry, but your gist link seems to be broken or outdatedGerminal
@VadimLevkovsky oh sorry, here is a working link: gist.github.com/mlaily/9423f1855bb176d52a327f5874915a97Hygroscope
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?Syndic
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.Paulson
restartmanager is perfect to detect which process is locking files. How about the directories? restartmanager can only handle files instead of directories. Can directories be pretended to be files or is it possible to use restartmanager for directories detection?@EricJ.@HygroscopeDentilingual
@Dentilingual I don't think Windows supports locking a directory. Locked files within a directory can prevent the directory from being removed.Paulson
@EricJ. for example, Create a folder; Open cmd and cd into it; Delete it using Explorer; It says "Folder In Use - The action can't be completed because the folder or a file in it is open in another program". I wanna check which program is using it. I find that filelocksmith can get it but too slow. So if RestartManager can do it, it will be perfect since it's faster. I tried to create symlink file for the folder and pass this symlink to RM. It returns no program using it though the folder is open with cmd. Maybe symlink hasn't same state with the target folder. No sure if other way to do thatDentilingual
It is a very bad idea to rely on dlls to do anything in .net. You will automatically prevent the code from being cross-platform. This answer is incorrectly assuming the user is programming in windows.Sparks
@JohnLord The question implicitly targeted Windows. It was the only target OS when asked. There is no bulletproof, platform-agnostic solution. You must call the OS to avoid concurrency issues. Even the current .NET implementation relies on OS code, e.g. Unix does not support named semaphores, so throws a PlatformNotSupportedException if a name is given. If you need a cross-platform solution, you can add implementations for other OS's and call the right native code. github.com/dotnet/runtime/blob/main/src/libraries/…Paulson
I
133

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.

Inhabiter answered 4/8, 2008 at 14:59 Comment(11)
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.Puttergill
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.Inhabiter
You could argue the same for access rights though it would of course be more unlikely.Jeseniajesh
@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.Tlaxcala
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?Pneumatic
@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?Inhabiter
@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.Pneumatic
It is now possible to get the process that is locking a file. See https://mcmap.net/q/54424/-how-to-check-for-file-lock-duplicatePaulson
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/…Syndic
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.Anastassia
If you're dealing with multiple files, checking if any are locked before updating helps keep things more atomicTweeddale
H
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;
}
Hospitable answered 1/4, 2011 at 11:19 Comment(1)
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.Culminant
P
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

Pelson answered 8/3, 2010 at 17:9 Comment(3)
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.Cockade
Actually, this is not a solution because you cannot create an instance of FileStream if the file is locked. (an exception will be thrown)Cerberus
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.Awed
U
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();
    }
}
Uralaltaic answered 3/1, 2013 at 3:41 Comment(8)
This is the only practical solution so far. And it works.Sacramentarian
Boooyyyyy... You better put some Thread.Sleep(200) in there and get off my CPU!Millian
What part do you want to sleep? Why?Uralaltaic
@Uralaltaic I guess, Paul Knopf meant to use Thread.Sleep between access tries.Puttergill
Try reading @PaulKnopf's comment without using an irate girlfriends voice in your head.Dubenko
In case of "FileNotFound", I got a negative value from GetHRForException() and thus an overflow-error (since our code is compiled with overflow-checks enabled). As far as I see, unchecked conversion is safe here.Cocker
@PaulKnopf Joking aside: There is no need for Thread.Sleep() as there is no loop in this code.Fizgig
@Fizgig There was a loop there originally before editsPuttergill
H
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(...);
}
Hearne answered 24/9, 2013 at 18:34 Comment(1)
Well, I was doing a kind of the same thing in my original answer till somebody decided to simplify it:) stackoverflow.com/posts/3202085/revisionsPuttergill
B
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.

Beeves answered 24/7, 2009 at 6:42 Comment(0)
D
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.

Diffident answered 17/8, 2008 at 18:17 Comment(0)
D
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.

Duplex answered 9/3, 2009 at 12:54 Comment(0)
V
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
}
Vaporizer answered 23/12, 2015 at 14:24 Comment(0)
P
-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;
}
Pneumatic answered 16/12, 2013 at 19:19 Comment(2)
You should consider a Using block for fileStarflower
Use System.Threading.Thread.Sleep(1000) instead of new System.Threading.ManualResetEvent(false).WaitOne(1000)Upbraid

© 2022 - 2024 — McMap. All rights reserved.