2011-09-27 146 views
0

我devloping管理我們定製的Windows服務的一個應用程序。我使用ServiceController對象來獲取所有服務,但在此之後我將如何區分哪些是我們的定製服務和哪些是系統服務?windows服務開發c#

我使用下面的代碼:

ListViewItem datalist;     

services = ServiceController.GetServices();          
ServiceList.Items.Clear(); 
foreach(ServiceController service in services) 
{          
    datalist = new System.Windows.Forms.ListViewItem(service.ServiceName.ToString()); 

    datalist.SubItems.Add(service.DisplayName);  
    datalist.SubItems.Add(service.Status.ToString());     
    ServiceList.Items.Add(datalist);          
}   
+0

你嘗試獲取並覈對姓名?你能顯示一些代碼嗎? –

+0

難道你只是想檢查'ServiceName'屬性嗎? –

+0

我將使用服務名稱屬性,但又是硬編碼的東西。 – Meraj

回答

0

app.config把你的服務的名稱。並在應用程序啓動時閱讀這些內容。

您可以使用http://csd.codeplex.com/創建自定義配置部分。

+0

感謝您的回覆,目前我只使用這種方式,但再次如果我添加新的服務,然後再次我需要修改我的app.config,這就是我不想要的。 – Meraj

+0

將您的公司名稱添加到服務的DisplayName屬性中。 – jgauffin

0

你可以把設置在.exe.config到每個服務 ,並觀察他們這樣

using System; 
using System.Collections.Generic; 
using System.Configuration; 
using System.IO; 
using System.Linq; 
using System.Management; 

class Program 
{ 
    static void Main(string[] args) 
    { 
     var searcher = 
      new ManagementObjectSearcher("SELECT * FROM Win32_Service WHERE Started=1 AND StartMode=\"Auto\""); 
     foreach (ManagementObject service in searcher.Get()) 
     { 
      foreach (var prop in service.Properties) 
      { 
       if (prop.Name != "PathName" || prop.Value == null) 
        continue; 
       var cmdLine = prop.Value.ToString(); 
       var path = cmdLine.SplitCommandLine().ToArray()[0] + ".config"; 
       if (File.Exists(path)) 
       { 
        var serviceConfig = ConfigurationManager.OpenExeConfiguration(path); 
/***/ 
       } 
       break; 
      } 
     } 
    } 
} 

SplitCommand

static class SplitCommand 
{ 
    public static IEnumerable<string> Split(this string str, Func<char, bool> controller) 
    { 
     int nextPiece = 0; for (int c = 0; c < str.Length; c++) 
     { 
      if (controller(str[c])) 
      { yield return str.Substring(nextPiece, c - nextPiece); nextPiece = c + 1; } 
     } yield return str.Substring(nextPiece); 
    } 
    public static IEnumerable<string> SplitCommandLine(this string commandLine) 
    { 
     bool inQuotes = false; 
     return commandLine.Split(c => 
     { 
      if (c == '\"') 
       inQuotes = !inQuotes; return !inQuotes && c == ' '; 
     }).Select(arg => arg.Trim().TrimMatchingQuotes('\"')).Where(arg => !string.IsNullOrEmpty(arg)); 
    } 
    public static string TrimMatchingQuotes(this string input, char quote) 
    { 
     if ((input.Length >= 2) && (input[0] == quote) && (input[input.Length - 1] == quote)) 
      return input.Substring(1, input.Length - 2); 
     return input; 
    } 
}