I've used the following function to find a java program by passing in identifying command line arguments like the path to the java executable and the class called and maybe a jar name or a property definition or two just to be sure. Once you have a process id, it is simple to create a Process using Process.GetProcessByValue(id) but you don't need that for your code, just check the returned id.HasValue.
/// <summary>
/// Return the first process id with matching values in the command line.
/// </summary>
/// <param name="args">
/// Values in the command line to match (case insensitive).
/// </param>
/// <returns>
/// The process id of the first matching process found; null on no match.
/// </returns>
public static int? ProcessIdOf(params string[] args)
{
using (var mos = new ManagementObjectSearcher(
"SELECT ProcessId,CommandLine FROM Win32_Process"))
{
foreach (ManagementObject mo in mos.Get())
{
var commandLine = (string)mo["CommandLine"] ?? string.Empty;
for (int i = 0;; ++i)
{
if (i == args.Length)
{
return int.Parse(mo["ProcessId"].ToString());
}
if (commandLine.IndexOf(
args[i],
StringComparison.InvariantCultureIgnoreCase) == -1)
{
break;
}
}
}
}
return null;
}
Some oddities in this code - I don't use the SELECT x,y FROM z WHERE y LIKE "%z%" construct because I didn't want to bother dealing with escape characters. Also, I don't really know what type a ProcessId is so I just cast it to a string and parse it as an int - I think I tried to do an unchecked cast to int and that threw an exception (from here it is supposed to be a uin32). The code above works.