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

如何在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() 

我使用过程类但没有结果

您可以使用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(); 

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

在这种情况下:

 var mysql = new System.ServiceProcess.ServiceController("mysql"); if (mysql .Status == ServiceControllerStatus.Stopped) { mysql.Start(); } 

您需要将“/ c”开关传递给cmd.exe

 pstart.Arguments = "/c net start mysql"