gpt4 book ai didi

c# - 使用 taskkill 停止 Windows 服务

转载 作者:可可西里 更新时间:2023-11-01 09:33:59 30 4
gpt4 key购买 nike

我需要帮助使用 C# 终止 Windows 服务,现在使用以下选项终止服务:

从命令:

sc queryex ServiceName

发现服务的PID

taskkill /pid 1234(exemple) /f

最佳答案

为了便于阅读,但如果您明白我的意思,我会使用单独的方法 IsServiceInstalled、IsServiceRunning、StopService 等将服务交互分离到它自己的类中。

此外,通过停止服务,它应该已经终止了进程,但我也包括了你将如何做类似的事情。如果服务不会停止,而您是通过终止进程来停止它,如果您有权访问它,我会查看服务代码是否未正确构建。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceProcess;
using System.Diagnostics;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ServiceController sc = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName.Equals("MyServiceNameHere"));
if (sc != null)
{
if (sc.Status.Equals(ServiceControllerStatus.Running))
{
sc.Stop();

Process[] procs = Process.GetProcessesByName("MyProcessName");
if (procs.Length > 0)
{
foreach (Process proc in procs)
{
//do other stuff if you need to find out if this is the correct proc instance if you have more than one
proc.Kill();
}
}
}
}
}
}
}

关于c# - 使用 taskkill 停止 Windows 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23014152/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com