Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2017
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.76 KB | None | 0 0
  1. using System.Runtime.InteropServices;
  2. using System.Diagnostics;
  3.  
  4. static public class FileUtil
  5. {
  6. [StructLayout(LayoutKind.Sequential)]
  7. struct RM_UNIQUE_PROCESS
  8. {
  9. public int dwProcessId;
  10. public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime;
  11. }
  12.  
  13. const int RmRebootReasonNone = 0;
  14. const int CCH_RM_MAX_APP_NAME = 255;
  15. const int CCH_RM_MAX_SVC_NAME = 63;
  16.  
  17. enum RM_APP_TYPE
  18. {
  19. RmUnknownApp = 0,
  20. RmMainWindow = 1,
  21. RmOtherWindow = 2,
  22. RmService = 3,
  23. RmExplorer = 4,
  24. RmConsole = 5,
  25. RmCritical = 1000
  26. }
  27.  
  28. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
  29. struct RM_PROCESS_INFO
  30. {
  31. public RM_UNIQUE_PROCESS Process;
  32.  
  33. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_APP_NAME + 1)]
  34. public string strAppName;
  35.  
  36. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_SVC_NAME + 1)]
  37. public string strServiceShortName;
  38.  
  39. public RM_APP_TYPE ApplicationType;
  40. public uint AppStatus;
  41. public uint TSSessionId;
  42. [MarshalAs(UnmanagedType.Bool)]
  43. public bool bRestartable;
  44. }
  45.  
  46. [DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
  47. static extern int RmRegisterResources(uint pSessionHandle,
  48. UInt32 nFiles,
  49. string[] rgsFilenames,
  50. UInt32 nApplications,
  51. [In] RM_UNIQUE_PROCESS[] rgApplications,
  52. UInt32 nServices,
  53. string[] rgsServiceNames);
  54.  
  55. [DllImport("rstrtmgr.dll", CharSet = CharSet.Auto)]
  56. static extern int RmStartSession(out uint pSessionHandle, int dwSessionFlags, string strSessionKey);
  57.  
  58. [DllImport("rstrtmgr.dll")]
  59. static extern int RmEndSession(uint pSessionHandle);
  60.  
  61. [DllImport("rstrtmgr.dll")]
  62. static extern int RmGetList(uint dwSessionHandle,
  63. out uint pnProcInfoNeeded,
  64. ref uint pnProcInfo,
  65. [In, Out] RM_PROCESS_INFO[] rgAffectedApps,
  66. ref uint lpdwRebootReasons);
  67.  
  68. /// <summary>
  69. /// Find out what process(es) have a lock on the specified file.
  70. /// </summary>
  71. /// <param name="path">Path of the file.</param>
  72. /// <returns>Processes locking the file</returns>
  73. /// <remarks>See also:
  74. /// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373661(v=vs.85).aspx
  75. /// http://wyupdate.googlecode.com/svn-history/r401/trunk/frmFilesInUse.cs (no copyright in code at time of viewing)
  76. ///
  77. /// </remarks>
  78. static public List<Process> WhoIsLocking(string path)
  79. {
  80. uint handle;
  81. string key = Guid.NewGuid().ToString();
  82. List<Process> processes = new List<Process>();
  83.  
  84. int res = RmStartSession(out handle, 0, key);
  85. if (res != 0) throw new Exception("Could not begin restart session. Unable to determine file locker.");
  86.  
  87. try
  88. {
  89. const int ERROR_MORE_DATA = 234;
  90. uint pnProcInfoNeeded = 0,
  91. pnProcInfo = 0,
  92. lpdwRebootReasons = RmRebootReasonNone;
  93.  
  94. string[] resources = new string[] { path }; // Just checking on one resource.
  95.  
  96. res = RmRegisterResources(handle, (uint)resources.Length, resources, 0, null, 0, null);
  97.  
  98. if (res != 0) throw new Exception("Could not register resource.");
  99.  
  100. //Note: there's a race condition here -- the first call to RmGetList() returns
  101. // the total number of process. However, when we call RmGetList() again to get
  102. // the actual processes this number may have increased.
  103. res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons);
  104.  
  105. if (res == ERROR_MORE_DATA)
  106. {
  107. // Create an array to store the process results
  108. RM_PROCESS_INFO[] processInfo = new RM_PROCESS_INFO[pnProcInfoNeeded];
  109. pnProcInfo = pnProcInfoNeeded;
  110.  
  111. // Get the list
  112. res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);
  113. if (res == 0)
  114. {
  115. processes = new List<Process>((int)pnProcInfo);
  116.  
  117. // Enumerate all of the results and add them to the
  118. // list to be returned
  119. for (int i = 0; i < pnProcInfo; i++)
  120. {
  121. try
  122. {
  123. processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId));
  124. }
  125. // catch the error -- in case the process is no longer running
  126. catch (ArgumentException) { }
  127. }
  128. }
  129. else throw new Exception("Could not list processes locking resource.");
  130. }
  131. else if (res != 0) throw new Exception("Could not list processes locking resource. Failed to get size of result.");
  132. }
  133. finally
  134. {
  135. RmEndSession(handle);
  136. }
  137.  
  138. return processes;
  139. }
  140. }
  141.  
  142. string fileName = @"c:aaa.doc";//Path to locked file
  143.  
  144. Process tool = new Process();
  145. tool.StartInfo.FileName = "handle.exe";
  146. tool.StartInfo.Arguments = fileName+" /accepteula";
  147. tool.StartInfo.UseShellExecute = false;
  148. tool.StartInfo.RedirectStandardOutput = true;
  149. tool.Start();
  150. tool.WaitForExit();
  151. string outputTool = tool.StandardOutput.ReadToEnd();
  152.  
  153. string matchPattern = @"(?<=s+pid:s+)b(d+)b(?=s+)";
  154. foreach(Match match in Regex.Matches(outputTool, matchPattern))
  155. {
  156. Process.GetProcessById(int.Parse(match.Value)).Kill();
  157. }
  158.  
  159. using System;
  160. using System.Collections;
  161. using System.Diagnostics;
  162. using System.Management;
  163. using System.IO;
  164.  
  165. static class Module1
  166. {
  167. static internal ArrayList myProcessArray = new ArrayList();
  168. private static Process myProcess;
  169.  
  170. public static void Main()
  171. {
  172. string strFile = "c:\windows\system32\msi.dll";
  173. ArrayList a = getFileProcesses(strFile);
  174. foreach (Process p in a)
  175. {
  176. Debug.Print(p.ProcessName);
  177. }
  178. }
  179.  
  180. private static ArrayList getFileProcesses(string strFile)
  181. {
  182. myProcessArray.Clear();
  183. Process[] processes = Process.GetProcesses();
  184. int i = 0;
  185. for (i = 0; i <= processes.GetUpperBound(0) - 1; i++)
  186. {
  187. myProcess = processes[i];
  188. //if (!myProcess.HasExited) //This will cause an "Access is denied" error
  189. if (myProcess.Threads.Count > 0)
  190. {
  191. try
  192. {
  193. ProcessModuleCollection modules = myProcess.Modules;
  194. int j = 0;
  195. for (j = 0; j <= modules.Count - 1; j++)
  196. {
  197. if ((modules[j].FileName.ToLower().CompareTo(strFile.ToLower()) == 0))
  198. {
  199. myProcessArray.Add(myProcess);
  200. break;
  201. // TODO: might not be correct. Was : Exit For
  202. }
  203. }
  204. }
  205. catch (Exception exception)
  206. {
  207. //MsgBox(("Error : " & exception.Message))
  208. }
  209. }
  210. }
  211.  
  212. return myProcessArray;
  213. }
  214. }
  215.  
  216. using System.Management;
  217. using System.IO;
  218.  
  219. static class Module1
  220. {
  221. static internal ArrayList myProcessArray = new ArrayList();
  222. private static Process myProcess;
  223.  
  224. public static void Main()
  225. {
  226.  
  227. string strFile = "c:\windows\system32\msi.dll";
  228. ArrayList a = getFileProcesses(strFile);
  229. foreach (Process p in a) {
  230. Debug.Print(p.ProcessName);
  231. }
  232. }
  233.  
  234.  
  235. private static ArrayList getFileProcesses(string strFile)
  236. {
  237. myProcessArray.Clear();
  238. Process[] processes = Process.GetProcesses;
  239. int i = 0;
  240. for (i = 0; i <= processes.GetUpperBound(0) - 1; i++) {
  241. myProcess = processes(i);
  242. if (!myProcess.HasExited) {
  243. try {
  244. ProcessModuleCollection modules = myProcess.Modules;
  245. int j = 0;
  246. for (j = 0; j <= modules.Count - 1; j++) {
  247. if ((modules.Item(j).FileName.ToLower.CompareTo(strFile.ToLower) == 0)) {
  248. myProcessArray.Add(myProcess);
  249. break; // TODO: might not be correct. Was : Exit For
  250. }
  251. }
  252. }
  253. catch (Exception exception) {
  254. }
  255. //MsgBox(("Error : " & exception.Message))
  256. }
  257. }
  258. return myProcessArray;
  259. }
  260. }
  261.  
  262. Imports System.Management
  263. Imports System.IO
  264.  
  265. Module Module1
  266. Friend myProcessArray As New ArrayList
  267. Private myProcess As Process
  268.  
  269. Sub Main()
  270.  
  271. Dim strFile As String = "c:windowssystem32msi.dll"
  272. Dim a As ArrayList = getFileProcesses(strFile)
  273. For Each p As Process In a
  274. Debug.Print(p.ProcessName)
  275. Next
  276. End Sub
  277.  
  278.  
  279. Private Function getFileProcesses(ByVal strFile As String) As ArrayList
  280. myProcessArray.Clear()
  281. Dim processes As Process() = Process.GetProcesses
  282. Dim i As Integer
  283. For i = 0 To processes.GetUpperBound(0) - 1
  284. myProcess = processes(i)
  285. If Not myProcess.HasExited Then
  286. Try
  287. Dim modules As ProcessModuleCollection = myProcess.Modules
  288. Dim j As Integer
  289. For j = 0 To modules.Count - 1
  290. If (modules.Item(j).FileName.ToLower.CompareTo(strFile.ToLower) = 0) Then
  291. myProcessArray.Add(myProcess)
  292. Exit For
  293. End If
  294. Next j
  295. Catch exception As Exception
  296. 'MsgBox(("Error : " & exception.Message))
  297. End Try
  298. End If
  299. Next i
  300. Return myProcessArray
  301. End Function
  302. End Module
  303.  
  304. public static class MurderProcess
  305. {
  306. public static void Murder(string strFile)
  307. {
  308. ArrayList a = getFileProcesses(strFile);
  309. foreach (Process p in a)
  310. {
  311. p.Kill();
  312. p.WaitForExit(10000);
  313. }
  314. }
  315.  
  316. public static ArrayList getFileProcesses(string strFile)
  317. {
  318. var myProcessArray = new ArrayList();
  319. Process myProcess;
  320. myProcessArray.Clear();
  321. Process[] processes = Process.GetProcesses();
  322. int i = 0;
  323. for (i = 0; i <= processes.GetUpperBound(0) - 1; i++)
  324. {
  325. myProcess = processes[i];
  326. if (!myProcess.HasExited)
  327. {
  328. try
  329. {
  330. ProcessModuleCollection modules = myProcess.Modules;
  331. int j = 0;
  332. for (j = 0; j <= modules.Count - 1; j++)
  333. {
  334. if ((modules[j].FileName.ToLower().CompareTo(strFile.ToLower()) == 0))
  335. {
  336. myProcessArray.Add(myProcess);
  337. break;
  338. }
  339. }
  340. }
  341. catch { }
  342. }
  343. }
  344. return myProcessArray;
  345. }
  346. }
  347.  
  348. public void KillProcessesAssociatedToFile(string file)
  349. {
  350. GetProcessesAssociatedToFile(file).ForEach(x =>
  351. {
  352. x.Kill();
  353. x.WaitForExit(10000);
  354. });
  355. }
  356.  
  357. public List<Process> GetProcessesAssociatedToFile(string file)
  358. {
  359. return Process.GetProcesses()
  360. .Where(x => !x.HasExited
  361. && x.Modules.Cast<ProcessModule>().ToList()
  362. .Exists(y => y.FileName.ToLowerInvariant() == file.ToLowerInvariant())
  363. ).ToList();
  364. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement