Check if a specific exe file is running

Viewed 69584

I want to know how i can check a program in a specific location if it is running. For example there are two locations for test.exe in c:\loc1\test.exe and c:\loc2\test.exe. I only wanted to know if c:\loc1\test.exe is running and not all instances of test.exe.

8 Answers

Something like this. GetMainModuleFileName helps to access x64 process from x86.

[DllImport("kernel32.dll")]
public static extern bool QueryFullProcessImageName(IntPtr hprocess, int dwFlags, StringBuilder lpExeName, out int size);

private bool CheckRunningProcess(string processName, string path) {

    var processes = Process.GetProcessesByName(processName);

    foreach(var process in processes) {

        var name = GetMainModuleFileName(process);
        if(name == null)
            continue;

        if(string.Equals(name, path, StringComparison.InvariantCultureIgnoreCase))
            return true;
    }

    return false;
}

// Get x64 process module name from x86 process
private static string GetMainModuleFileName(Process process, int buffer = 1024) {

    var fileNameBuilder = new StringBuilder(buffer);
    int bufferLength = fileNameBuilder.Capacity + 1;

    return QueryFullProcessImageName(process.Handle, 0, fileNameBuilder, out bufferLength)
        ? fileNameBuilder.ToString()
        : null;
}
Related