Reputation: 577
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
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
Reputation: 14521
You won't find notepad.exe
, since its ProcessName
is just notepad
.
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
Reputation: 31231
This has always worked for me
if(Process.GetProcessesByName("notepad").Length == 0)
{
// do stuff
}
Upvotes: 1
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