Windows服务开发c#

本文关键字:开发 服务 Windows | 更新日期: 2023-09-27 18:09:52

我正在开发一个应用程序来管理我们定制的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);                                    
}           

Windows服务开发c#

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

您可以使用http://csd.codeplex.com/创建一个自定义配置节

您可以将设置放在。exe中。配置到您的每个服务然后像这样观察它们

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