我尝试使用程序检查进程是否存在。为什么Process.GetProcessesByName()始终为空?
using System;
using System.Diagnostics;
using System.ServiceProcess;
namespace ServProInfo
{
class Program
{
public static int IfProcessExist(string processName)
{
try
{
Process[] targetProcess = Process.GetProcessesByName(processName);
int proLen = targetProcess.Length;
if (proLen == 0)
{
Console.WriteLine("The process does NOT exist or has exited...");
return 0;
}
Console.WriteLine("The process status is: Running");
return 1;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + "\r\n" + ex.StackTrace + "\r\n" + ex.Source);
return -1;
}
}
static void Main(string[] args)
{
string type = args[0];
string name = args[1];
switch (type)
{
case "p":
IfProcessExist(name);
break;
}
}
}
}
然而,该方法[] targetProcess常是无效,甚至当我设置processName作为存在进程的名称。
我该如何纠正该程序?
你能提供的例子,你是如何运行的程序?像:你传递给程序的参数? – 2013-04-10 10:34:42
我猜这个过程没有找到。你的过程是一个32位的过程,而另一个过程是64位?这是最常见的故障模式。 – 2013-04-10 10:34:48
如果你尝试使用扩展名来获取进程,请将其删除,例如尝试获得“svchost”而不是“svchost.exe” – ilansch 2014-08-04 08:58:26