Domanda

I have the following code in my system.

 private void killprocess()
    {
        Process[] procs = null;
        try
        {
            procs = Process.GetProcessesByName("notepad");
            Process NotepadProc = procs[0];
            if (!NotepadProc.HasExited)
            {
                NotepadProc.Kill();
            }
            else if (procs != null)
                foreach (Process p in procs)
                {
                    p.Dispose();
                }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

The program gets notepad from the list of process and ends it. My problem is that if notepad is not running I get this error. enter image description here

I know what it is telling however I cant seem to get the code right to first check run an if statement that checks if notepad is running and if it is not running not not close is.

È stato utile?

Soluzione

IndexOutOfRangeException will occour at this step: Process NotepadProc = procs[0];

You could check the length of your list.

Example:

if(procs.Length == 0)
   return;

or

if(procs.Length > 0)
{
   your code
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top