使用C#启动和停止服务 [英] Start and stop a service using c#

查看:58
本文介绍了使用C#启动和停止服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想停止一项服务,然后在停止完成后重新启动该服务.我正在使用c#,并产生了以下代码.问题是:如果启动了服务,它将停止服务,但不会重新启动服务.如果该服务在下次调用时停止,它将仅启动该服务.

I would like to stop a service and then restart the service once it has finished stopping. I am using c# and have produced the following code. The problem is: if the service is started it will stop the service but not restart the service. If the service is stopped the next time the function is called it will just start the service.

string strCmdText1, strCmdText2;
strCmdText1 = "NET STOP \"AdmnService\"";
strCmdText2 = "NET START \"AdmnService\"";
System.Diagnostics.Process.Start("CMD.exe", "/C" + strCmdText1);
System.Diagnostics.Process.Start("CMD.exe", "/C" + strCmdText2);

是否可以将命令串联成一行?我不确定/C会做什么,但是也许还有其他开关可以执行两个命令.

Is there a way to concatenate the commands into one line? I am not sure what the /C does but perhaps there is some other switch to execute two commands.

推荐答案

您可以使用 ServiceController (在System.ServiceProcess .Net 4程序集中).这是一个简单的控制台应用程序,显示了如何:

You can use ServiceController (in the System.ServiceProcess .Net 4 assembly). Here's a simple Console application showing how:

        ServiceController controller = new ServiceController("AdmnService");
        controller.Stop();

        controller.WaitForStatus(ServiceControllerStatus.Stopped);
        Console.WriteLine("Service status: " + controller.Status);

        controller.Start();
        Console.WriteLine("Service status: " + controller.Status);

这篇关于使用C#启动和停止服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆