Home >Backend Development >C++ >How to Reliably Get a Process's File Path in C# and Avoid Win32Exceptions?

How to Reliably Get a Process's File Path in C# and Avoid Win32Exceptions?

Susan Sarandon
Susan SarandonOriginal
2025-01-03 12:31:40701browse

How to Reliably Get a Process's File Path in C# and Avoid Win32Exceptions?

Avoiding Win32 Exception When Accessing Process.MainModule.FileName in C#

In C#, attempting to retrieve the FileName property of a process' MainModule may occasionally trigger a Win32Exception, especially when working with 64-bit platforms. To address this issue, Jeff Mercado's solution offers a reliable approach.

Adapted Code:

To simplify the process, here's an adaptation of Mercado's code to obtain the file path of a specific process:

string s = GetMainModuleFilepath(2011);

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 method queries the Windows Management Instrumentation (WMI) for the ExecutablePath property of the process with the specified process ID. If a matching process is found, its file path is returned. Otherwise, null is returned.

The above is the detailed content of How to Reliably Get a Process's File Path in C# and Avoid Win32Exceptions?. 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