|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Diagnostics; |
| 4 | +using System.Runtime.InteropServices; |
| 5 | + |
| 6 | +// Expanded with some helpers from: https://code.msdn.microsoft.com/windowsapps/How-to-know-the-process-704839f4/ |
| 7 | +// Uses Windows Restart Manager. |
| 8 | +// A more involved and cross platform solution to this problem is here: https://github.com/cklutz/LockCheck |
| 9 | + |
| 10 | + |
| 11 | +namespace FileLockFinder |
| 12 | +{ |
| 13 | + public class LockFinder |
| 14 | + { |
| 15 | + |
| 16 | + /// <summary> |
| 17 | + /// Method <c>FindLockedProcessName</c> Retrieve the first process name |
| 18 | + /// that is locking the file at the specified path |
| 19 | + /// </summary> |
| 20 | + /// <param name="path">The path of a file with a write lock held by a |
| 21 | + /// process</param> |
| 22 | + /// <resturns>The name of the first process found with a lock</resturns> |
| 23 | + /// <exception cref="Exception"> |
| 24 | + /// Thrown when the file path is not locked |
| 25 | + /// </exception> |
| 26 | + static public string FindLockedProcessName(string path) |
| 27 | + { |
| 28 | + var list = FindLockProcesses(path); |
| 29 | + if(list.Count == 0) { throw new Exception( |
| 30 | + "No processes are locking the path specified"); } |
| 31 | + return list[0].ProcessName; |
| 32 | + } |
| 33 | + |
| 34 | + /// <summary> |
| 35 | + /// Method <c>CheckIfFileIsLocked</c> Check if the file specified has a |
| 36 | + /// write lock held by a process |
| 37 | + /// </summary> |
| 38 | + /// <param name="path">The path of a file being checked if a write lock |
| 39 | + /// held by a process</param> |
| 40 | + /// <returns>true when one or more processes with lock</returns> |
| 41 | + static public bool CheckIfFileIsLocked(string path) |
| 42 | + { |
| 43 | + var list = FindLockProcesses(path); |
| 44 | + if(list.Count > 0) { return true; } |
| 45 | + return false; |
| 46 | + } |
| 47 | + |
| 48 | + /// <summary> |
| 49 | + /// Used to find processes holding a lock on the file. This would cause |
| 50 | + /// other usage, such as file truncation or write opretions to throw |
| 51 | + /// IOException if an exclusive lock is attempted. |
| 52 | + /// </summary> |
| 53 | + /// <param name="path">Path being checked</param> |
| 54 | + /// <returns>List of processes holding file lock to path</returns> |
| 55 | + /// <exception cref="Exception"></exception> |
| 56 | + static public List<Process> FindLockProcesses(string path) |
| 57 | + { |
| 58 | + uint handle; |
| 59 | + string key = Guid.NewGuid().ToString(); |
| 60 | + List<Process> processes = new List<Process>(); |
| 61 | + |
| 62 | + int res = RmStartSession(out handle, 0, key); |
| 63 | + if (res != 0) |
| 64 | + { |
| 65 | + throw new Exception("Could not begin restart session. " + |
| 66 | + "Unable to determine file locker."); |
| 67 | + } |
| 68 | + |
| 69 | + try |
| 70 | + { |
| 71 | + const int ERROR_MORE_DATA = 234; |
| 72 | + uint pnProcInfoNeeded = 0, pnProcInfo = 0, |
| 73 | + lpdwRebootReasons = RmRebootReasonNone; |
| 74 | + string[] resources = new string[] { path }; |
| 75 | + |
| 76 | + res = RmRegisterResources(handle, (uint)resources.Length, |
| 77 | + resources, 0, null, 0, null); |
| 78 | + if (res != 0) |
| 79 | + { |
| 80 | + throw new Exception("Could not register resource."); |
| 81 | + } |
| 82 | + res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, |
| 83 | + ref lpdwRebootReasons); |
| 84 | + if (res == ERROR_MORE_DATA) |
| 85 | + { |
| 86 | + RM_PROCESS_INFO[] processInfo = |
| 87 | + new RM_PROCESS_INFO[pnProcInfoNeeded]; |
| 88 | + pnProcInfo = pnProcInfoNeeded; |
| 89 | + // Get the list. |
| 90 | + res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, |
| 91 | + processInfo, ref lpdwRebootReasons); |
| 92 | + if (res == 0) |
| 93 | + { |
| 94 | + processes = new List<Process>((int)pnProcInfo); |
| 95 | + for (int i = 0; i < pnProcInfo; i++) |
| 96 | + { |
| 97 | + try |
| 98 | + { |
| 99 | + processes.Add(Process.GetProcessById(processInfo[i]. |
| 100 | + Process.dwProcessId)); |
| 101 | + } |
| 102 | + catch (ArgumentException) { } |
| 103 | + } |
| 104 | + } |
| 105 | + else |
| 106 | + { |
| 107 | + throw new Exception("Could not list processes locking resource"); |
| 108 | + } |
| 109 | + } |
| 110 | + else if (res != 0) |
| 111 | + { |
| 112 | + throw new Exception("Could not list processes locking resource." + |
| 113 | + "Failed to get size of result."); |
| 114 | + } |
| 115 | + } |
| 116 | + catch (Exception exception) |
| 117 | + { |
| 118 | + Console.WriteLine(exception.Message); |
| 119 | + } |
| 120 | + finally |
| 121 | + { |
| 122 | + RmEndSession(handle); |
| 123 | + } |
| 124 | + |
| 125 | + return processes; |
| 126 | + } |
| 127 | + private const int RmRebootReasonNone = 0; |
| 128 | + private const int CCH_RM_MAX_APP_NAME = 255; |
| 129 | + private const int CCH_RM_MAX_SVC_NAME = 63; |
| 130 | + |
| 131 | + [StructLayout(LayoutKind.Sequential)] |
| 132 | + struct RM_UNIQUE_PROCESS |
| 133 | + { |
| 134 | + public int dwProcessId; |
| 135 | + public System.Runtime.InteropServices. |
| 136 | + ComTypes.FILETIME ProcessStartTime; |
| 137 | + } |
| 138 | + [DllImport("rstrtmgr.dll", |
| 139 | + CharSet = CharSet.Auto, SetLastError = true)] |
| 140 | + static extern int RmGetList(uint dwSessionHandle, |
| 141 | + out uint pnProcInfoNeeded, |
| 142 | + ref uint pnProcInfo, |
| 143 | + [In, Out] RM_PROCESS_INFO[] rgAffectedApps, |
| 144 | + ref uint lpdwRebootReasons); |
| 145 | + [StructLayout(LayoutKind.Sequential, |
| 146 | + CharSet = CharSet.Auto)] |
| 147 | + struct RM_PROCESS_INFO |
| 148 | + { |
| 149 | + public RM_UNIQUE_PROCESS Process; |
| 150 | + [MarshalAs(UnmanagedType.ByValTStr, |
| 151 | + SizeConst = CCH_RM_MAX_APP_NAME + 1)] |
| 152 | + public string strAppName; |
| 153 | + [MarshalAs(UnmanagedType.ByValTStr, |
| 154 | + SizeConst = CCH_RM_MAX_SVC_NAME + 1)] |
| 155 | + public string strServiceShortName; |
| 156 | + public RM_APP_TYPE ApplicationType; |
| 157 | + public uint AppStatus; |
| 158 | + public uint TSSessionId; |
| 159 | + [MarshalAs(UnmanagedType.Bool)] |
| 160 | + public bool bRestartable; |
| 161 | + } |
| 162 | + |
| 163 | + enum RM_APP_TYPE |
| 164 | + { |
| 165 | + RmUnknownApp = 0, |
| 166 | + RmMainWindow = 1, |
| 167 | + RmOtherWindow = 2, |
| 168 | + RmService = 3, |
| 169 | + RmExplorer = 4, |
| 170 | + RmConsole = 5, |
| 171 | + RmCritical = 1000 |
| 172 | + } |
| 173 | + |
| 174 | + [DllImport("rstrtmgr.dll", |
| 175 | + CharSet = CharSet.Auto, |
| 176 | + SetLastError = true)] |
| 177 | + static extern int RmRegisterResources( |
| 178 | + uint pSessionHandle, |
| 179 | + UInt32 nFiles, |
| 180 | + string[] rgsFilenames, |
| 181 | + UInt32 nApplications, |
| 182 | + [In] RM_UNIQUE_PROCESS[] rgApplications, |
| 183 | + UInt32 nServices, string[] rgsServiceNames); |
| 184 | + |
| 185 | + [DllImport("rstrtmgr.dll", |
| 186 | + CharSet = CharSet.Auto, |
| 187 | + SetLastError = true)] |
| 188 | + static extern int RmStartSession( |
| 189 | + out uint pSessionHandle, |
| 190 | + int dwSessionFlags, |
| 191 | + string strSessionKey); |
| 192 | + |
| 193 | + [DllImport("rstrtmgr.dll", |
| 194 | + CharSet = CharSet.Auto, |
| 195 | + SetLastError = true)] |
| 196 | + static extern int RmEndSession(uint pSessionHandle); |
| 197 | + } |
| 198 | +} |
0 commit comments