When working with processes, I do not understand why this does not work

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

    }
}

what this code should do is do textbox1.text, "2" if 2 notepads work, etc., but it does nothing. I do not see any problem with this code, so I am here.

+3
source share
3 answers

Firstly, if no notebooks work, you won’t do anything. Perhaps he should write 0 in a textBox?

I suggest rewriting the code as follows:

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 the opportunity to easily debug and see which items are in the process list.

In addition, your process may be Notepad, not Notepad. So I replaced your equality check with a String.Compare call.

+4
source

"notepad.exe" - ... ,

if (pro.ProcessName == "notepad")

if (pro.ProcessName.StartsWith("notepad", StringComparison.OrdinalIgnoreCase)) 

, .

+4

CWell, first of all, you must move the variable declaration outside the foreach loop.

And secondly, you have to do both alexD and agent-j, change the way the string is compared:

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

Hope this helps

+2
source

All Articles