'C# Get process id from ExecutablePath

I'm trying to get a process id in C# from ExecutablePath. When I enter wmiQueryString into WMI Tester, it works without a problem. But if I enter it into the code, it throws me an invalid query error.

What am I doing wrong?

My code:

using System;
using System.Management;
using System.Diagnostics;
using System.Linq;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string wmiQueryString = "SELECT ProcessId, ExecutablePath FROM Win32_Process WHERE ExecutablePath ='C:\\Program Files (x86)\\ASUS\\AI Suite III\\AISuite3.exe'";
            using (var searcher = new ManagementObjectSearcher(wmiQueryString))
            {
                using (var results = searcher.Get())
                {
                    ManagementObject mo = results.Cast<ManagementObject>().FirstOrDefault();
                    if (mo != null)
                    {
                        int procId = 0;
 
                        int.TryParse(mo["ProcessId"].ToString(), out procId);
 
                        Console.WriteLine(procId);
 
                    }
                }
            }
 
           
 
        }
 
    }
}


Solution 1:[1]

The approach via the management objects looks rather complicated. Is there a special reason for this? Else you could just use .NETs standard Process class for obtaining a process ID.

Process[] processCollection = Process.GetProcesses();
foreach (Process p in processCollection)
{
    fullPath = p.MainModule.FileName;
    if (fullPath == "c:\\abcd.exe")
    {
        return p.Id;
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1