我嘗試使用程序檢查進程是否存在。爲什麼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