如何在c#中使用net stop命令启动/停止服务

Sur*_*esh 8 c# process

如何在c#中使用net stop命令启动/停止服务

Dim pstart As New ProcessStartInfo
Dim path As String = Environment.GetFolderPath(Environment.SpecialFolder.System)
Dim p As New Process
pstart.FileName = path + "\cmd.exe"
pstart.UseShellExecute = False
pstart.CreateNoWindow = True
pstart.WorkingDirectory = path
pstart.FileName = "cmd.exe"
pstart.Arguments = " net start mysql"
p.StartInfo = pstart
p.Start()
Run Code Online (Sandbox Code Playgroud)

我使用过程类但没有结果

Kir*_*tan 25

您可以使用ServiceController类来启动/停止本地/远程计算机上的特定服务,而不是像Process.Start那样使用原始方法.

using System.ServiceProcess;
ServiceController controller  = new ServiceController();

controller.MachineName = ".";
controller.ServiceName = "mysql";

// Start the service
controller.Start();

// Stop the service
controller.Stop();
Run Code Online (Sandbox Code Playgroud)

  • 您还需要添加对System.ServiceProcess的引用. (2认同)

Ale*_*man 6

您可能希望查看System.ServiceProcess.ServiceController类,该类为Windows的Services提供托管接口.

在这种情况下:

var mysql = new System.ServiceProcess.ServiceController("mysql");
if (mysql .Status == ServiceControllerStatus.Stopped) {
   mysql.Start();
}
Run Code Online (Sandbox Code Playgroud)