/// <summary> /// Method to get the process path /// </summary> /// <param name="processid"></param> /// <returns>string</returns> public static string GetProcessPath(int processid) { var pathBuffer = new StringBuilder(512); // Try the GetModuleFileName method first since it's the fastest. // May return ACCESS_DENIED (due to VM_READ flag) if the process is not owned by the current user. // Will fail if we are compiled as x86 and we're trying to open a 64 bit process...not allowed. var hprocess = OpenProcess(ProcessAccessRights.QueryInformation | ProcessAccessRights.VirtualMemoryRead, false, processid); if (hprocess != IntPtr.Zero) { try { if (PsApi.GetModuleFileNameEx(hprocess, IntPtr.Zero, pathBuffer, (uint)pathBuffer.Capacity) > 0) { return(pathBuffer.ToString()); } } finally { CloseHandle(hprocess); } } hprocess = OpenProcess(ProcessAccessRights.QueryInformation, false, processid); if (hprocess != IntPtr.Zero) { try { // Try this method for Vista or higher operating systems var size = (uint)pathBuffer.Capacity; if (Environment.OSVersion.Version.Major >= 6 && QueryFullProcessImageName(hprocess, 0, pathBuffer, ref size) && size > 0) { return(pathBuffer.ToString()); } // Try the GetProcessImageFileName method if (PsApi.GetProcessImageFileName(hprocess, pathBuffer, (uint)pathBuffer.Capacity) > 0) { var dospath = pathBuffer.ToString(); foreach (var drive in Environment.GetLogicalDrives()) { if (QueryDosDevice(drive.TrimEnd('\\'), pathBuffer, (uint)pathBuffer.Capacity) > 0 && dospath.StartsWith(pathBuffer.ToString())) { return(drive + dospath.Remove(0, pathBuffer.Length)); } } } } finally { CloseHandle(hprocess); } } return(null); }
/// <summary> /// Retrieves the fully qualified path for the file containing the specified module. /// </summary> /// <param name="hProcess">IntPtr, A handle to the process that contains the module.</param> /// <param name="hModule">IntPtr A handle to the module. If this parameter is NULL, GetModuleFileNameEx returns the path of the executable file of the process specified in hProcess.</param> /// <returns>string</returns> public static string GetModuleFilename(IntPtr hProcess, IntPtr hModule) { unsafe { const int capacity = 512; var pathBuffer = stackalloc char[capacity]; var nrCharacters = PsApi.GetModuleFileNameEx(hProcess, hModule, pathBuffer, capacity); if (nrCharacters > 0) { return(new string(pathBuffer, 0, nrCharacters)); } return(null); } }