I have this basic code that will check for notepad running every minute.
namespace Watcher
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; ; i--)
{
foreach (Process clsProcess in Process.GetProcesses())
{
if (clsProcess.ProcessName.Contains("notepad"))
{
Console.WriteLine("True");
}
Console.WriteLine("NFalse");
}
Thread.Sleep(10000);
}
}
}
}
The problem is that it returns "NFalse" for every running process (It will print 100 of them for example). How can I just make this print once to show that the process is not running?
Refactor your code.
You're doing too much in one method. Put your code that checks to see if notepad is running into a separate method:
static bool CheckIfProcessIsRunning(string nameSubstring)
{
foreach (Process clsProcess in Process.GetProcesses())
{
if (clsProcess.ProcessName.Contains(nameSubstring))
{
return true;
}
}
return false;
}
You could simplify this further using LINQ:
static bool CheckIfProcessIsRunning(string nameSubstring)
{
return Process.GetProcesses().Any(p => p.ProcessName.Contains(nameSubstring));
}
Once you have written this method, all that remains is to call it and print the right message depending on whether it returns true or false.
while (true)
{
string message = CheckIfProcessIsRunning("notepad") ? "True" : "NFalse";
Console.WriteLine(message);
Thread.Sleep(10000);
}
Now instead of one long method with complex logic, you have two very simple methods.
You just need to check the process you are interested in. Don't bother looping over all the running processes. Use Process.GetProcessByName().
for (int i = 0; ; i--)
{
Process[] processes = Process.GetProcessByName("notepad++"); // Without extension
if(processes.Length > 0){
Console.WriteLine("True");
}
else{
Console.WriteLine("False");
}
Thread.Sleep(10000);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With