How to check for file lock?

220,524

Solution 1

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.

Solution 2

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

}

Solution 3

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.

Solution 4

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;
}

Solution 5

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

Share:
220,524

Related videos on Youtube

ricree
Author by

ricree

Updated on September 09, 2021

Comments

  • ricree
    ricree almost 3 years

    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.

    • user3001801
      user3001801 over 14 years
      The trouble is that an IOException could be thrown for many reasons other than a locked file.
    • Eric J.
      Eric J. over 10 years
      This is an old question, and all of the old answers are incomplete or wrong. I added a complete and correct answer.
    • amalgamate
      amalgamate over 8 years
      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().
  • DixonD
    DixonD over 13 years
    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.
  • Lasse V. Karlsen
    Lasse V. Karlsen over 13 years
    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.
  • BrainSlugs83
    BrainSlugs83 over 12 years
    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.
  • Zé Carlos
    Zé Carlos over 12 years
    Actually, this is not a solution because you cannot create an instance of FileStream if the file is locked. (an exception will be thrown)
  • Alex S
    Alex S almost 12 years
    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.
  • Contango
    Contango over 11 years
    This is the only practical solution so far. And it works.
  • ctusch
    ctusch about 11 years
    You could argue the same for access rights though it would of course be more unlikely.
  • Thiru
    Thiru about 11 years
    @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.
  • kite
    kite almost 11 years
    too bad opening sqlite db used by firefox will leave program hang waiting for just the exception to be thrown
  • Bart Calixto
    Bart Calixto over 10 years
    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?
  • Lasse V. Karlsen
    Lasse V. Karlsen over 10 years
    @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?
  • Bart Calixto
    Bart Calixto over 10 years
    @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.
  • Serj Sagan
    Serj Sagan over 10 years
    The only answer here that actually answers the OP question... nice!
  • DixonD
    DixonD over 10 years
    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
  • Eric J.
    Eric J. over 10 years
    It is now possible to get the process that is locking a file. See stackoverflow.com/a/20623302/141172
  • Eric J.
    Eric J. over 10 years
    @kite: There is a better way now stackoverflow.com/a/20623302/141172
  • jocull
    jocull about 10 years
    What if between return false and your attempt to open the file again something else snatches it up? Race conditions ahoy!
  • Paul Knopf
    Paul Knopf about 10 years
    Boooyyyyy... You better put some Thread.Sleep(200) in there and get off my CPU!
  • Tristan
    Tristan about 10 years
    What part do you want to sleep? Why?
  • VoteCoffee
    VoteCoffee about 10 years
    You should consider a Using block for file
  • Endrju
    Endrju almost 10 years
    Use System.Threading.Thread.Sleep(1000) instead of new System.Threading.ManualResetEvent(false).WaitOne(1000)
  • DixonD
    DixonD almost 10 years
    @Tristan I guess, Paul Knopf meant to use Thread.Sleep between access tries.
  • Coder14
    Coder14 over 9 years
    Will this work if the file is located on a network share and the file is possibly locked on another pc?
  • Eric J.
    Eric J. over 9 years
    @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.
  • Daniel Revell
    Daniel Revell over 9 years
    What do the other HRESULTS that can come back from this mean? How did you know that 32 and 33 represent types of locking?
  • DixonD
    DixonD over 9 years
  • Jonathan D
    Jonathan D over 9 years
    I just used this and it does work across the network.
  • SerG
    SerG about 9 years
    Code looks taken from here, it contains some flaws and should be improved with The Old New Thing
  • Eric J.
    Eric J. about 9 years
    @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.
  • Phil Cooper
    Phil Cooper over 8 years
    Try reading @PaulKnopf's comment without using an irate girlfriends voice in your head.
  • Tormod
    Tormod over 8 years
    @SerG Did (either of) you update the answer? Both the links appear to be outdated.
  • Eric J.
    Eric J. over 8 years
    @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=8283
  • SerG
    SerG over 8 years
    @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.
  • Melvyn
    Melvyn about 8 years
    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...
  • RenniePet
    RenniePet about 8 years
    Maybe Microsoft has changed that web page, but it currently doesn't include error codes ending with 32 or 33.
  • DixonD
    DixonD about 8 years
    @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
  • Andreas
    Andreas almost 8 years
    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.
  • NickG
    NickG over 7 years
    @PaulKnopf Joking aside: There is no need for Thread.Sleep() as there is no loop in this code.
  • BartoszKP
    BartoszKP about 7 years
    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.
  • Fandango68
    Fandango68 about 7 years
    Is there a VS2005 solution please?
  • Eric J.
    Eric J. about 7 years
    @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).
  • DixonD
    DixonD about 7 years
    @NickG There was a loop there originally before edits
  • Vadim Levkovsky
    Vadim Levkovsky almost 7 years
    @Yaurthek sorry, but your gist link seems to be broken or outdated
  • Melvyn
    Melvyn almost 7 years
    @VadimLevkovsky oh sorry, here is a working link: gist.github.com/mlaily/9423f1855bb176d52a327f5874915a97
  • brianary
    brianary about 6 years
    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."docs.microsoft.com/en-us/dotnet/standard/design-guidelines/…
  • brianary
    brianary about 6 years
    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?
  • Eric J.
    Eric J. about 6 years
    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.
  • Alexandre M
    Alexandre M over 5 years
    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.
  • taiji123
    taiji123 almost 5 years
    @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;
  • Alexander Høst
    Alexander Høst over 2 years
    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.