216 [StructLayout(LayoutKind.Sequential)]
217 struct RM_UNIQUE_PROCESS
219 public int dwProcessId;
220 public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime;
223 const int RmRebootReasonNone = 0;
224 const int CCH_RM_MAX_APP_NAME = 255;
225 const int CCH_RM_MAX_SVC_NAME = 63;
238 [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
239 struct RM_PROCESS_INFO
241 public RM_UNIQUE_PROCESS Process;
243 [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_APP_NAME + 1)]
244 public string strAppName;
246 [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_SVC_NAME + 1)]
247 public string strServiceShortName;
249 public RM_APP_TYPE ApplicationType;
250 public uint AppStatus;
251 public uint TSSessionId;
252 [MarshalAs(UnmanagedType.Bool)]
253 public bool bRestartable;
256 [DllImport(
"rstrtmgr.dll", CharSet = CharSet.Unicode)]
257 static extern int RmRegisterResources(uint pSessionHandle,
259 string[] rgsFilenames,
260 UInt32 nApplications,
261 [In] RM_UNIQUE_PROCESS[] rgApplications,
263 string[] rgsServiceNames);
265 [DllImport(
"rstrtmgr.dll", CharSet = CharSet.Auto)]
266 static extern int RmStartSession(out uint pSessionHandle,
int dwSessionFlags,
string strSessionKey);
268 [DllImport(
"rstrtmgr.dll")]
269 static extern int RmEndSession(uint pSessionHandle);
271 [DllImport(
"rstrtmgr.dll")]
272 static extern int RmGetList(uint dwSessionHandle,
273 out uint pnProcInfoNeeded,
275 [In, Out] RM_PROCESS_INFO[] rgAffectedApps,
276 ref uint lpdwRebootReasons);
277 static public List<Process>
Locking(
string path)
280 string key = Guid.NewGuid().ToString();
281 List<Process> processes =
new List<Process>();
283 int res = RmStartSession(out handle, 0, key);
286 throw new Exception(
"Could not begin restart session. Unable to determine file locker.");
290 const int ERROR_MORE_DATA = 234;
291 uint pnProcInfoNeeded = 0,
293 lpdwRebootReasons = RmRebootReasonNone;
295 string[] resources =
new string[] { path };
297 res = RmRegisterResources(handle, (uint)resources.Length, resources, 0,
null, 0,
null);
300 throw new Exception(
"Could not register resource.");
305 res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo,
null, ref lpdwRebootReasons);
307 if (res == ERROR_MORE_DATA)
310 RM_PROCESS_INFO[] processInfo =
new RM_PROCESS_INFO[pnProcInfoNeeded];
311 pnProcInfo = pnProcInfoNeeded;
314 res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);
318 processes =
new List<Process>((
int)pnProcInfo);
322 for (
int i = 0; i < pnProcInfo; i++)
326 processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId));
329 catch (ArgumentException) { }
333 throw new Exception(
"Could not list processes locking resource.");
336 throw new Exception(
"Could not list processes locking resource. Failed to get size of result.");
340 RmEndSession(handle);