2017-05-16 45 views
0

早上好,C#從windows服務獲取結果

我已經開發一個C#的WinForms簡單aplication管理「阿帕奇」窗口服務,我可以啓動,停止等操作。

我的情景:

  • 我打開Apache的配置文件,並更改任何行,我做它的原因的錯誤配置(我知道)。
  • 當我嘗試啓動Apache服務,這不能啓動,因爲配置文件語法不正確(我知道)。
  • 消息error從服務註冊在Windows事件查看器(我知道)。
  • 我想在我的C#WinForms應用程序得到這個消息時,它是更多鈔票?

我的代碼:

public void ManageService(string serviceName, int Operation) 
     { 
      ServiceController sc = new ServiceController(); 
      sc.ServiceName = serviceName; 
      try 
      { 
       switch (Operation) 
       { 
        case 1: sc.Stop(); ; break; 
        case 2: sc.Start(); break; 
       } 
      } 
      catch (InvalidOperationException e) 
      { 

      } 
     } 

如何修改這個代碼可以捕捉到apache服務的消息。

PD。對不起,如果我的英語不好,)。

+0

您是否嘗試捕獲捕獲異常並將消息返回給調用者? –

+0

@Karen佩恩,我試着用e.Message在抓,但從來沒有打電話, – Jorny

回答

0

好吧,不是回答每說,但不知道如何把它變成註釋。請注意使用WaitForStatus和一個屬性的錯誤消息。這是相當殘缺的。

using System; 
using System.Linq; 
using System.ServiceProcess; 

namespace Revenue.Common.Utility 
{ 
    public class WindowsServices 
    { 
     private string _ErrorMessage; 
     public string ErrorMessage { get { return _ErrorMessage; } } 
     /// <summary> 
     /// Stop a Windows service service name 
     /// </summary> 
     /// <param name="ServiceName"></param> 
     /// <remarks> 
     /// A service does not stop instantly, so WaitForStatus method 
     /// is used to 'wait' until the service has stopped. If the 
     /// caller becomes unresponsive then there may be issues with 
     /// the service stopping outside of code. 
     /// </remarks> 
     public void StopService(string ServiceName) 
     { 
      ServiceController sc = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == ServiceName); 
      if (sc == null) 
       return; 

      if (sc.Status == ServiceControllerStatus.Running) 
      { 
       try 
       { 
        sc.Stop(); 
        sc.WaitForStatus(ServiceControllerStatus.Stopped); 
       } 
       catch (InvalidOperationException e) 
       { 
        _ErrorMessage = e.Message; 
       } 
      } 
     } 
     /// <summary> 
     /// Start a Windows service by service name 
     /// </summary> 
     /// <param name="ServiceName"></param> 
     public void StartService(string ServiceName) 
     { 
      ServiceController sc = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == ServiceName); 
      if (sc == null) 
       return; 

      sc.ServiceName = ServiceName; 
      if (sc.Status == ServiceControllerStatus.Stopped) 
      { 
       try 
       { 
        sc.Start(); 
        sc.WaitForStatus(ServiceControllerStatus.Running); 
       } 
       catch (InvalidOperationException) 
       { 
        _ErrorMessage = e.Message; 
       } 
      } 
     } 
    } 
} 
+0

我試圖與WaitForStatus,但我的形式是無限frozzen – Jorny

+0

一直在使用這個沒有問題,在這裏,從未發生過問題,所以我沒有什麼建設性的補充。 –