Coder Perfect

How can I see if a file is locked? [duplicate]


Is there a method to see if a file is locked without having to use a try/catch block?

The only approach I can think of right now is to simply open the file and catch any System.IO.IOException.

Asked by ricree

Solution #1

When I was confronted with a similar issue, I came up 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)
                return File.Open(_fileName, FileMode.Open, fileAccess, Fileshare.None); 
            catch (IOException e)
                if (!IsFileLocked(e))
                if (++tries > _numberOfTries)
                    throw new MyCustomException("The file is locked too long: " + e.Message, e);

    private static bool IsFileLocked(IOException exception)
        int errorCode = Marshal.GetHRForException(exception) & ((1 << 16) - 1);
        return errorCode == 32 || errorCode == 33;

    // other code


Answered by DixonD

Solution #2

The other responses are based on outdated information. This one offers a superior answer.

It used to be impossible to gather a reliable list of processes that were locking a file since Windows didn’t keep track of that information. That data is now tracked in order to enable the Restart Manager API. Beginning with Windows Vista and Windows Server 2008, the Restart Manager API is available (Restart Manager: Run-time Requirements).

I wrote some code that accepts a file’s location and produces a ListProcess> of all the processes that are locking it.

static public class FileUtil
        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;
        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);

    static extern int RmEndSession(uint pSessionHandle);

    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:
    /// (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.");

            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++)
                        // catch the error -- in case the process is no longer running
                        catch (ArgumentException) { }
                    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.");                    

        return processes;


Another article with sample code on how to utilize the Restart Manager API can be found here.

Answered by Eric J.

Solution #3

Unfortunately, no, and, when you think about it, such information would be useless anyhow because the file could be locked at any moment (read: short timespan).

Why do you need to know if the file is locked in the first place? Knowing this may enable us to provide you with better guidance in the future.

If your code looked like this, it would be:

if not locked then
    open and update file

Then, between the two lines, another process might easily lock the file, resulting in the exceptions you were attempting to avoid in the first place.

Answered by Lasse V. Karlsen

Solution #4

Provides a list of programs that must be closed in order to continue, much like an installer.

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;

Answered by Aralmo

Solution #5

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



Answered by Sergio Vicente

Post is based on