Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with processes, I don't get why this isn't working

Tags:

c#

.net

process

foreach (Process pro in Process.GetProcesses())
{
    int i = 0;
    if (pro.ProcessName == "notepad")
    {
        i++;
        textBox1.Text = Convert.ToString(i);

    }
}

what this code supposed to do is making textbox1.text, "2" if 2 notepad is running etc., however it doesn't do anything at all. I can't see any problem looking at this code, so I am here.

like image 748
Foresp Avatar asked Dec 29 '25 02:12

Foresp


1 Answers

First, if no notepads is running - you code won't do anything. Probably it should write 0 to textBox?

I'll suggest rewriting code like that:

var processes = Process.GetProcesses().Select(p => p.ProcessName).ToList();
int count = processes.Count(name => String.Compare(name, "notepad", StringComparison.OrdinalIgnoreCase) == 0);
textBox1.Text = Convert.ToString(count);

You will have ability to debug easily and see which elements are in your processes list.

Moreover, your process could be "Notepad" not "notepad". Thus I replaced your equality check with String.Compare call.

like image 83
Ivan Danilov Avatar answered Dec 31 '25 16:12

Ivan Danilov