internal static Collection <Process> GetProcessForFileLockCore(KernelTransaction transaction, Collection <string> filePaths, PathFormat pathFormat) { if (!NativeMethods.IsAtLeastWindowsVista) { throw new PlatformNotSupportedException(new Win32Exception((int)Win32Errors.ERROR_OLD_WIN_VERSION).Message); } if (null == filePaths) { throw new ArgumentNullException("filePaths"); } if (filePaths.Count == 0) { throw new ArgumentOutOfRangeException("filePaths", "No paths specified."); } var isLongPath = pathFormat == PathFormat.LongFullPath; var allPaths = isLongPath ? new Collection <string>(filePaths) : new Collection <string>(); if (!isLongPath) { foreach (var path in filePaths) { allPaths.Add(Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck)); } } uint sessionHandle; var success = NativeMethods.RmStartSession(out sessionHandle, 0, Guid.NewGuid().ToString()) == Win32Errors.ERROR_SUCCESS; var lastError = Marshal.GetLastWin32Error(); if (!success) { NativeError.ThrowException(lastError); } var processes = new Collection <Process>(); try { // A snapshot count of all running processes. var processesFound = (uint)Process.GetProcesses().Length; uint lpdwRebootReasons = 0; success = NativeMethods.RmRegisterResources(sessionHandle, (uint)allPaths.Count, allPaths.ToArray(), 0, null, 0, null) == Win32Errors.ERROR_SUCCESS; lastError = Marshal.GetLastWin32Error(); if (!success) { NativeError.ThrowException(lastError); } GetList: var processInfo = new NativeMethods.RM_PROCESS_INFO[processesFound]; var processesTotal = processesFound; lastError = NativeMethods.RmGetList(sessionHandle, out processesFound, ref processesTotal, processInfo, ref lpdwRebootReasons); // There would be no need for this because we already have a/the total number of running processes. if (lastError == Win32Errors.ERROR_MORE_DATA) { goto GetList; } if (lastError != Win32Errors.ERROR_SUCCESS) { NativeError.ThrowException(lastError); } for (var i = 0; i < processesTotal; i++) { try { processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId)); } // MSDN: The process specified by the processId parameter is not running. The identifier might be expired. catch (ArgumentException) {} } } finally { NativeMethods.RmEndSession(sessionHandle); } return(processes.Count == 0 ? null : processes); }
private NativeMethods.RM_PROCESS_INFO[] ListAppsInternal(out uint arrayLength, out NativeMethods.RM_REBOOT_REASON rebootReasons) { int ret; uint arrayLengthNeeded = 1; NativeMethods.RM_PROCESS_INFO[] processInfo; do { arrayLength = arrayLengthNeeded; processInfo = new NativeMethods.RM_PROCESS_INFO[arrayLength]; ret = NativeMethods.RmGetList(_sessionHandle, out arrayLengthNeeded, ref arrayLength, processInfo, out rebootReasons); } while (ret == WindowsUtils.Win32ErrorMoreData); if (ret != 0) throw BuildException(ret); return processInfo; }