Home >Backend Development >C++ >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!