windows服务开发c#

时间:2011-09-27 06:08:01

标签: c# windows-services

我正在开发一个管理我们定制的Windows服务的应用程序。我正在使用ServiceController对象来获取所有服务,但之后我将如何区分哪个是我们的自定义服务,哪个是系统服务?

我正在使用以下代码:

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);                                    
}           

2 个答案:

答案 0 :(得分:0)

将您的服务名称放在app.config中。并在您的应用程序启动时阅读。

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

答案 1 :(得分: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;
    }
}