A fork of Eusth's IPA
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

152 lines
5.6KB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Runtime.InteropServices;
  5. namespace IPA.Patcher
  6. {
  7. static public class FileUtil
  8. {
  9. [StructLayout(LayoutKind.Sequential)]
  10. struct RM_UNIQUE_PROCESS
  11. {
  12. public int dwProcessId;
  13. public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime;
  14. }
  15. const int RmRebootReasonNone = 0;
  16. const int CCH_RM_MAX_APP_NAME = 255;
  17. const int CCH_RM_MAX_SVC_NAME = 63;
  18. enum RM_APP_TYPE
  19. {
  20. RmUnknownApp = 0,
  21. RmMainWindow = 1,
  22. RmOtherWindow = 2,
  23. RmService = 3,
  24. RmExplorer = 4,
  25. RmConsole = 5,
  26. RmCritical = 1000
  27. }
  28. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
  29. struct RM_PROCESS_INFO
  30. {
  31. public RM_UNIQUE_PROCESS Process;
  32. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_APP_NAME + 1)]
  33. public string strAppName;
  34. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_SVC_NAME + 1)]
  35. public string strServiceShortName;
  36. public RM_APP_TYPE ApplicationType;
  37. public uint AppStatus;
  38. public uint TSSessionId;
  39. [MarshalAs(UnmanagedType.Bool)] public bool bRestartable;
  40. }
  41. [DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
  42. static extern int RmRegisterResources(uint pSessionHandle,
  43. UInt32 nFiles,
  44. string[] rgsFilenames,
  45. UInt32 nApplications,
  46. [In] RM_UNIQUE_PROCESS[] rgApplications,
  47. UInt32 nServices,
  48. string[] rgsServiceNames);
  49. [DllImport("rstrtmgr.dll", CharSet = CharSet.Auto)]
  50. static extern int RmStartSession(out uint pSessionHandle, int dwSessionFlags, string strSessionKey);
  51. [DllImport("rstrtmgr.dll")]
  52. static extern int RmEndSession(uint pSessionHandle);
  53. [DllImport("rstrtmgr.dll")]
  54. static extern int RmGetList(uint dwSessionHandle,
  55. out uint pnProcInfoNeeded,
  56. ref uint pnProcInfo,
  57. [In, Out] RM_PROCESS_INFO[] rgAffectedApps,
  58. ref uint lpdwRebootReasons);
  59. /// <summary>
  60. /// Find out what process(es) have a lock on the specified file.
  61. /// </summary>
  62. /// <param name="path">Path of the file.</param>
  63. /// <returns>Processes locking the file</returns>
  64. /// <remarks>See also:
  65. /// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373661(v=vs.85).aspx
  66. /// http://wyupdate.googlecode.com/svn-history/r401/trunk/frmFilesInUse.cs (no copyright in code at time of viewing)
  67. ///
  68. /// </remarks>
  69. static public List<Process> WhoIsLocking(string path)
  70. {
  71. uint handle;
  72. string key = Guid.NewGuid().ToString();
  73. List<Process> processes = new List<Process>();
  74. int res = RmStartSession(out handle, 0, key);
  75. if (res != 0)
  76. throw new Exception("Could not begin restart session. Unable to determine file locker.");
  77. try
  78. {
  79. const int ERROR_MORE_DATA = 234;
  80. uint pnProcInfoNeeded = 0,
  81. pnProcInfo = 0,
  82. lpdwRebootReasons = RmRebootReasonNone;
  83. string[] resources = new string[] {path}; // Just checking on one resource.
  84. res = RmRegisterResources(handle, (uint) resources.Length, resources, 0, null, 0, null);
  85. if (res != 0)
  86. throw new Exception("Could not register resource.");
  87. //Note: there's a race condition here -- the first call to RmGetList() returns
  88. // the total number of process. However, when we call RmGetList() again to get
  89. // the actual processes this number may have increased.
  90. res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons);
  91. if (res == ERROR_MORE_DATA)
  92. {
  93. // Create an array to store the process results
  94. RM_PROCESS_INFO[] processInfo = new RM_PROCESS_INFO[pnProcInfoNeeded];
  95. pnProcInfo = pnProcInfoNeeded;
  96. // Get the list
  97. res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);
  98. if (res == 0)
  99. {
  100. processes = new List<Process>((int) pnProcInfo);
  101. // Enumerate all of the results and add them to the
  102. // list to be returned
  103. for (int i = 0; i < pnProcInfo; i++)
  104. {
  105. try
  106. {
  107. processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId));
  108. }
  109. // catch the error -- in case the process is no longer running
  110. catch (ArgumentException)
  111. {
  112. }
  113. }
  114. }
  115. else
  116. throw new Exception("Could not list processes locking resource.");
  117. }
  118. else if (res != 0)
  119. throw new Exception("Could not list processes locking resource. Failed to get size of result.");
  120. }
  121. finally
  122. {
  123. RmEndSession(handle);
  124. }
  125. return processes;
  126. }
  127. }
  128. }