Click here to Skip to main content
16,015,504 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
ServiceController myService = new ServiceController();
            myService.ServiceName = "ImapiService";
            string svcStatus = myService.Status.ToString();
                if (svcStatus == "Running"){
                    myService.Stop();
                    myService.Refresh();

}
 string svcStatu = myService.Status.ToString();
                if (svcStatu == "Stopped"){
                    myService.Start();
                    myService.Refresh();
}



When I put the break point of the first string and continue to step by step this code is works but when I didn't put the any break point code will be given an error why??..Can you help me?
Posted
Comments
Kumarbs 5-Aug-14 5:26am    
What is the error you got?
bora1891 5-Aug-14 7:01am    
ServiceController myService = new ServiceController();
myService.ServiceName = "ImapiService";
string svcStatus = myService.Status.ToString();
if (svcStatus == "Running"){
myService.Stop();
myService.Refresh();
myService.Start();
}
if My code change like this the error will be at myService.Start(); and error is:Cannot start service MSSQL$SQLEXPRESS on computer.

but if my code like this
ServiceController myService = new ServiceController();
myService.ServiceName = "ImapiService";
string svcStatus = myService.Status.ToString();
if (svcStatus == "Running"){
myService.Stop();
myService.Refresh();

}
string svcStatu = myService.Status.ToString();
if (svcStatu == "Stopped"){
myService.Start();
myService.Refresh();
}

program will not to step into second if statement.. why?
TcJoshJohnson 5-Aug-14 12:32pm    
First of all, why are you calling ToString on ServiceController.Status? Why not use the provided enum? Also, there are more states to a service than "Running" and "Stopped". Instead of using inclusive checks, you should use exclusive checks. For example, instead of "if the service is running, do this" try "if the service is not stopped or stopping, do this".

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900