Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the Process.GetProcessesByName() always null?

Tags:

c#

I try to use program to check the process if it exists.

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;
            }  
        }
    }
}

However, the Process[] targetProcess is alway null, even when I set processName as an exist process's name.

How could I correct the program?

like image 980
SUT Avatar asked Apr 10 '13 10:04

SUT


1 Answers

You can try the following: (works fine for me)

Process[] targetProcess = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(processName));
like image 163
Tomtom Avatar answered Oct 08 '22 07:10

Tomtom