我正在尝试使用C#获取java Process对象。 问题是我的计算机上运行了几个java进程。
以下是我选择获取流程的方式:
Process[] processes = Process.GetProcessesByName("java");
foreach(Process proc in processes){
//I need a filter here to get the correct process.
}
java Process也由我的C#程序控制,如下所示:
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = javahome + "\\bin\\java.exe";
startInfo.Arguments = "-jar Example.jar port=88888";
startInfo.WorkingDirectory = "\\testFolder";
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
Process proc = new Process();
proc.StartInfo = startInfo;
proc.Start();
我想要的是通过Process数组来检查哪一个与我在另一个程序中启动的Process对象具有相同的Arguments。 但问题是当我这样做的时候:
Console.WriteLine(proc.StartInfo.Arguments);
我发现里面什么都没有,即使我知道这是我在另一个程序中开始的过程。这让我很困惑。
有谁知道这个问题?
答案 0 :(得分:1)
你不能这样做。当你启动一个进程时,将该进程的处理程序保存在一个字典中,其中值是进程参数,这是我看到你存档的唯一方法。
Dictionary<IntPtr, string> processArguments = new Dictionary<IntPtr,string>();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = javahome + "\\bin\\java.exe";
startInfo.Arguments = "-jar Example.jar port=88888";
startInfo.WorkingDirectory = "\\testFolder";
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
Process proc = new Process();
proc.StartInfo = startInfo;
proc.Start();
processArguments.Add(proc.Handle, javahome + "\\bin\\java.exe");
....
Process[] processes = Process.GetProcessesByName("java");
foreach (Process proc in processes)
{
var arguments = processArguments.Where(x => x.Key.Equals(proc.Handle)).FirstOrDefault().Value;
}
答案 1 :(得分:0)
您可以尝试使用LINQ,如下所示:
Process[] processes = Process.GetProcessesByName("java");
var fileteredProcess = from pro in processes
where (pro.StartInfo.WorkingDirectory == "workingDIR") &&
(pro.StartInfo.Arguments == "Arguments")
select pro;
foreach (var proc in fileteredProcess)
{
}
答案 2 :(得分:0)
以下是使用WMI的替代解决方案:
Process[] processes;
Process selectedProc = null;
int selectedProcId = 0;
// http://wutils.com/wmi/
// using System.Management;
ManagementScope scope = new ManagementScope("\\\\.\\ROOT\\cimv2");
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Process "
+ "WHERE Name = 'java.exe'");
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(scope, query);
ManagementObjectCollection queryCollection = searcher.Get();
foreach (ManagementObject m in queryCollection)
{
// access properties of the WMI object
Console.WriteLine("CommandLine : {0}", m["CommandLine"]);
Console.WriteLine("ProcessId : {0}", m["ProcessId"]);
if (m["CommandLine"].ToString().Contains("my pattern"))
{
selectedProcId = int.Parse(m["ProcessId"].ToString());
selectedProc = Process.GetProcessById(selectedProcId);
break;
}
}
if (selectedProc != null)
{
Console.WriteLine("Proc title {0}", selectedProc.MainWindowTitle);
}