Home > Backend Development > C++ > How to Avoid Win32Exceptions When Accessing Process.MainModule.FileName in C#?

How to Avoid Win32Exceptions When Accessing Process.MainModule.FileName in C#?

Susan Sarandon
Release: 2024-12-26 00:51:10
Original
857 people have browsed it

How to Avoid Win32Exceptions When Accessing Process.MainModule.FileName in C#?

Accessing Process.MainModule.FileName in C#: Avoiding Win32 Exceptions

When attempting to access the Process.MainModule.FileName property in C#, developers may encounter a Win32Exception. This exception is typically encountered while enumerating process modules on a 64-bit platform, despite recompiling the application for 32-bit (x86) or AnyCPU environments.

The code in question often takes the following form:

Process p = Process.GetProcessById(2011);
string s = proc_by_id.MainModule.FileName;
Copy after login

To address this issue, developers can leverage the code provided by Jeff Mercado, as suggested in the reference answer. This code has been adapted slightly to retrieve the filepath of a specific process:

string s = GetMainModuleFilepath(2011);
Copy after login

The GetMainModuleFilepath method utilizes Windows Management Instrumentation (WMI) to query the Win32_Process class for the ExecutablePath property:

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

By utilizing this approach, developers can circumvent the Win32Exception and successfully retrieve the MainModule.FileName for the specified process.

The above is the detailed content of How to Avoid Win32Exceptions When Accessing Process.MainModule.FileName in C#?. 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