/// <remarks>Copy from: https://stackoverflow.com/a/20623311/6116637</remarks>
public static class FileUtil
// ReSharper disable InconsistentNaming
// ReSharper disable FieldCanBeMadeReadOnly.Local
// ReSharper disable StringLiteralTypo
// ReSharper disable InlineOutVariableDeclaration
// ReSharper disable MemberCanBePrivate.Local
// ReSharper disable UnusedMember.Local
// ReSharper disable RedundantAssignment
[StructLayout(LayoutKind.Sequential)]
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;
const int ERROR_MORE_DATA = 234;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
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;
[MarshalAs(UnmanagedType.Bool)]
public bool bRestartable;
[DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
static extern int RmRegisterResources(uint pSessionHandle,
[In] RM_UNIQUE_PROCESS[]? rgApplications,
string[]? rgsServiceNames);
[DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
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,
[In, Out] RM_PROCESS_INFO[]? rgAffectedApps,
ref uint lpdwRebootReasons);
/// Find out what process(es) have a lock on the specified file.
/// <param name="path">Path of the file.</param>
/// <returns>Processes locking the file</returns>
/// 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)
public static List<Process>? WhoIsLocking(string path)
string key = Guid.NewGuid().ToString();
List<Process> processes = new List<Process>();
int res = RmStartSession(out handle, 0, key);
if (res != 0) return null;
uint pnProcInfoNeeded = 0,
lpdwRebootReasons = RmRebootReasonNone;
string[] resources = new string[] { path }; // Just checking on one resource.
res = RmRegisterResources(handle, (uint)resources.Length, resources, 0, null, 0, null);
//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;
res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);
processes = new List<Process>((int)pnProcInfo);
// Enumerate all of the results and add them to the
for (int i = 0; i < pnProcInfo; i++)
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.");
//throw new Exception("Could not list processes locking resource. Failed to get size of result.");