以下是一个示例代码,其中使用了C#语言来启动Windows服务并停止:
using System;
using System.ServiceProcess;
public class Program
{
public static void Main()
{
string serviceName = "MyService"; // 替换为你要启动和停止的服务名称
ServiceController serviceController = new ServiceController(serviceName);
try
{
// 启动服务
Console.WriteLine("Starting the service...");
serviceController.Start();
serviceController.WaitForStatus(ServiceControllerStatus.Running);
Console.WriteLine("Service started successfully.");
// 停止服务
Console.WriteLine("Stopping the service...");
serviceController.Stop();
serviceController.WaitForStatus(ServiceControllerStatus.Stopped);
Console.WriteLine("Service stopped successfully.");
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
}
}
请注意,你需要将代码中的serviceName
替换为你要启动和停止的服务的实际名称。