找出Windows服务的运行进程名称.NET 1.1

the*_*ker 7 c# .net-1.1 windows-services process

我们正在使用一个写得很糟糕的Windows服务,当我们尝试从代码中阻止它时,它将挂起.因此,我们需要找到与该服务相关的进程并将其终止.有什么建议?

Dan*_*son 13

您可以使用System.Management.MangementObjectSearcher获取服务的进程ID并System.Diagnostics.Process获取相应的Process实例并将其终止.

KillService()以下程序中的方法显示了如何执行此操作:

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Management;

namespace KillProcessApp {
    class Program {
        static void Main(string[] args) {
            KillService("YourServiceName");
        }

        static void KillService(string serviceName) {
            string query = string.Format(
                "SELECT ProcessId FROM Win32_Service WHERE Name='{0}'", 
                serviceName);
            ManagementObjectSearcher searcher = 
                new ManagementObjectSearcher(query);
            foreach (ManagementObject obj in searcher.Get()) {
                uint processId = (uint) obj["ProcessId"];
                Process process = null;
                try
                {
                    process = Process.GetProcessById((int)processId);
                }
                catch (ArgumentException)
                {
                    // Thrown if the process specified by processId
                    // is no longer running.
                }
                try
                {
                    if (process != null) 
                    {
                        process.Kill();
                    }
                }
                catch (Win32Exception)
                {
                    // Thrown if process is already terminating,
                    // the process is a Win16 exe or the process
                    // could not be terminated.
                }
                catch (InvalidOperationException)
                {
                    // Thrown if the process has already terminated.
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Ric*_*ard 5

WMI具有以下信息:Win32_Service类.

像WQL一样的查询

SELECT ProcessId FROM Win32_Service WHERE Name='MyServiceName'
Run Code Online (Sandbox Code Playgroud)

使用System.Management应该可以解决问题.

快速查看:taskllist.exe /svc和命令行中的其他工具.