Skip to content

Using return true and false

Mike Smith

Asked Nov 3, 2017, 6:20 AM EDT1 answer
Share
LinkedInX
Hello,
 
I'm not very familar with using return true and false.
 
I found this code and would like to understand how to best use it.
 
 
C#
public static bool IsServiceInstalled(string serviceName)
        {
            // get list of Windows services
            ServiceController[] services = ServiceController.GetServices();

            // try to find service name
            foreach (ServiceController service in services)
            {
                if (service.ServiceName == "ServiceNameHere")
                    return true;
                MessageBox.Show("true");
            }
            return false;
        }
 
 So, can someone show me a simple example of using this on say a form load.
 
Here is what I came up with so far.
 
Code
ServiceController[] services = ServiceController.GetServices();

If (services == "ServiceName"
{
   MessageBox.Show("Service: Found");
}
else
{
   MessageBox.Show("Service: Not Found");
}
 
Thanks for the help! 

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    1. public static bool IsServiceInstalled(string serviceName)  
    2. {  
    3. // get list of Windows services  
    4. ServiceController[] services = ServiceController.GetServices();  
    5. // try to find service name  
    6. foreach (ServiceController service in services)  
    7. {  
    8. if (service.ServiceName == "ServiceNameHere")  
    9. {  
    10. return true;  
    11. MessageBox.Show("true"); // This code will not execute  
    12. }  
    13. }  
    14. return false; // If the given service name is not match then it returns false.  
    15. }
    On the Form Load, you should use like,
    1. bool isServiceInstalled = IsServiceInstalled("pass_your_service_name");  
    2. MessageBox.Show("Service installed : " + isServiceInstalled );  
    Hope this helps you.
0