ace007
ace007

Reputation: 577

is process running , never works

I've always had problems with processes, I've never been able to check if a process is running for some reason and i've tried every snippet of code i could find via google but nothing has worked. I've tried different files too. so finally i will ask for help :) here is a snippet among many that has failed to detect even notepad.exe:

public bool IsProcessOpen(string name) {
    foreach (Process clsProcess in Process.GetProcesses()){
        if (clsProcess.ProcessName.Contains(name)){
            return true;
        }
    }
    return false;
}

I know how to call the method obviously but like all the others it returns false for any file thats running or not. is it some kind of bug?

Upvotes: 1

Views: 396

Answers (5)

Flane
Flane

Reputation: 111

This checks to see if a process is running and changes the color of a button. Be sure you have the name correct: some take dot exe and some do not. This is checking the system process'.

   Process[] proc = Process.GetProcessesByName("iexplore");
        if (proc.Length == 0)
        {
            btnlogon.BackColor = Color.OrangeRed;
        }
        else
        {
            btnlogon.BackColor = Color.LightGreen;
        }

Upvotes: 0

user2838722
user2838722

Reputation: 11

It will not work for stopped working process.

Upvotes: 1

Michal Klouda
Michal Klouda

Reputation: 14521

You won't find notepad.exe, since its ProcessName is just notepad.

enter image description here

You could trim the extension using:

Path.GetFileNameWithoutExtension(name)

Also you can reduce your method body to one line:

return Process.GetProcessesByName(Path.GetFileNameWithoutExtension(name)).Length > 0;

Upvotes: 3

Bali C
Bali C

Reputation: 31231

This has always worked for me

if(Process.GetProcessesByName("notepad").Length == 0)
{
    // do stuff
}

Upvotes: 1

Martin Liversage
Martin Liversage

Reputation: 106836

You method is fine. Perhaps you are having problems with upper and lower case? You can improve your check by mapping to upper case in the if statement:

clsProcess.ProcessName.ToUpperInvariant().Contains(name.ToUpperInvariant())

Then notepad, Notepad and NOTEPAD will all match the process named notepad.

Upvotes: 1

Related Questions