2013-02-26 600 views
3

我想停止服務,然後在服務完成停止後重新啓動服務。 我正在使用c#並生成了以下代碼。問題是:如果服務已啓動,它將停止服務,但不會重新啓動服務。如果服務在下次調用該函數時停止,它將只啓動該服務。使用c啓動和停止服務#

string strCmdText1, strCmdText2; 
strCmdText1 = "NET STOP \"AdmnService\""; 
strCmdText2 = "NET START \"AdmnService\""; 
System.Diagnostics.Process.Start("CMD.exe", "/C" + strCmdText1); 
System.Diagnostics.Process.Start("CMD.exe", "/C" + strCmdText2); 

有沒有辦法將命令連接成一行?我不確定/ C的功能,但可能還有其他一些開關執行兩個命令。

+0

你可以創建一個批處理文件來執行2個命令,然後使用c#來啓動批處理文件嗎? – Matt 2013-02-26 19:36:33

+0

正是我在想什麼。 – RandomUs1r 2013-02-26 19:36:59

回答

5

您可以使用ServiceController(在System.ServiceProcess .NET 4的組件)。這裏有一個簡單的控制檯應用程序顯示如何:

 ServiceController controller = new ServiceController("AdmnService"); 
     controller.Stop(); 

     controller.WaitForStatus(ServiceControllerStatus.Stopped); 
     Console.WriteLine("Service status: " + controller.Status); 

     controller.Start(); 
     Console.WriteLine("Service status: " + controller.Status); 
+0

這工作得很好! thnks – crh225 2013-02-26 20:14:22

1

使用ServiceController類可能更容易。

使用狀態屬性,你可以找到服務的狀態,並再次啓動它或者使用WaitForStatus方法將信號