c# process.mainModule win32异常

作者: zengde 分类: 笔记 发布时间: 2021-12-07 01:31

方法一:

private string GetMainModuleFilepath(int processId)
{
  string wmiQueryString = "SELECT ProcessId, ExecutablePath FROM Win32_Process WHERE ProcessId = " + processId;
  using (var searcher = new ManagementObjectSearcher(wmiQueryString))
  {
    using (var results = searcher.Get())
    {
      ManagementObject mo = results.Cast<ManagementObject>().FirstOrDefault();
      if (mo != null)
      {
          return (string)mo["ExecutablePath"];
      }
    }
  }
  return null;
}

方法二:

public static extern IntPtr OpenProcess(uint processAccess, bool bInheritHandle, int processId);

[DllImport("psapi.dll")]
static extern uint GetModuleFileNameEx(IntPtr hProcess, IntPtr hModule, [Out] StringBuilder lpBaseName, [In][MarshalAs(UnmanagedType.U4)] int nSize);

[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CloseHandle(IntPtr hObject);

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private string GetProcessName(int pid)
{
    var processHandle = OpenProcess(0x0400 | 0x0010, false, pid);

    if (processHandle == IntPtr.Zero)
    {
        return null;
    }

    const int lengthSb = 4000;

    var sb = new StringBuilder(lengthSb);

    string result = null;

    if (GetModuleFileNameEx(processHandle, IntPtr.Zero, sb, lengthSb) > 0)
    {
        //result = Path.GetFileName(sb.ToString());
        result = sb.ToString();
    }

    CloseHandle(processHandle);

    return result;
}