Home > Backend Development > C++ > How to Avoid Win32Exception When Getting a Process's Executable Path?

How to Avoid Win32Exception When Getting a Process's Executable Path?

Barbara Streisand
Release: 2024-12-28 01:09:10
Original
917 people have browsed it

How to Avoid Win32Exception When Getting a Process's Executable Path?

Working Around Win32Exception When Accessing Process.MainModule.FileName

When attempting to retrieve the file path for running processes through Process.MainModule.FileName, some processes may throw a Win32Exception due to an inability to list process modules. To address this issue, Jeff Mercado provided an alternative method.

The adapted C# code:

string s = GetMainModuleFilepath(2011);
Copy after login

Full function implementation:

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;
}
Copy after login

This approach utilizes the Windows Management Instrumentation (WMI) to query the specific process and retrieve its executable path without attempting to access its process modules. It avoids the error encountered when the Process.MainModule.FileName property is accessed directly.

The above is the detailed content of How to Avoid Win32Exception When Getting a Process's Executable Path?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template