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
Barbara StreisandOriginal
2024-12-28 01:09:10920browse

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);

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;
}

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!

Statement:
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