如何使用c#从java进程获得带有参数的ProcessStartInfo
本文关键字:参数 ProcessStartInfo 何使用 java 进程 | 更新日期: 2023-09-27 18:13:02
我试图通过使用c#获得java进程对象。问题是我的电脑上运行了几个java进程。
下面是我选择的获取Processes的方式:
Process[] processes = Process.GetProcessesByName("java");
foreach(Process proc in processes){
//I need a filter here to get the correct process.
}
java进程也由我的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对象具有相同的参数。但是问题是当我这样做的时候:
Console.WriteLine(proc.StartInfo.Arguments);
我发现里面什么都没有,即使我知道这是我在另一个程序中启动的进程。这让我很困惑。
有人知道这个问题吗?
你不能那样做。当您启动一个进程时,将该进程的处理程序保存在字典中,其中值是进程参数,这是我认为您存档该进程的唯一方法。
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;
}
你可以这样做,使用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)
{
}
这是使用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);
}