public class exeSysService
{
    // 使用sc.exe安装服务
    public static void InstallService(string serviceName, string executablePath)
    {
        Process process = new Process();
        ProcessStartInfo startInfo = new ProcessStartInfo
        {
            FileName = "sc.exe",
            Arguments = $"create \"{serviceName}\" binPath= \"{executablePath}\" start= auto",
            WindowStyle = ProcessWindowStyle.Hidden,
            Verb = "runas" // 请求管理员权限
        };
        process.StartInfo = startInfo;
        process.Start();
        process.WaitForExit();
        if (process.ExitCode == 0)
        {
            Console.WriteLine("服务安装成功!");
            StartService(serviceName); // 安装后启动服务
        }
        else
        {
            Console.WriteLine($"服务安装失败,错误代码: {process.ExitCode}");
        }
    }
    // 启动服务
    private static void StartService(string serviceName)
    {
        using (ServiceController service = new ServiceController(serviceName))
        {
            if (service.Status != ServiceControllerStatus.Running)
            {
                service.Start();
                service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(30));
                Console.WriteLine("服务已启动!");
            }
        }
    }
    // 停止并卸载服务
    public static void UninstallService(string serviceName)
    {
        StopService(serviceName); // 先停止服务
        Process process = new Process();
        ProcessStartInfo startInfo = new ProcessStartInfo
        {
            FileName = "sc.exe",
            Arguments = $"delete \"{serviceName}\"",
            WindowStyle = ProcessWindowStyle.Hidden,
            Verb = "runas" // 请求管理员权限
        };
        process.StartInfo = startInfo;
        process.Start();
        process.WaitForExit();
        if (process.ExitCode == 0)
            Console.WriteLine("服务卸载成功!");
        else
            Console.WriteLine($"服务卸载失败,错误代码: {process.ExitCode}");
    }
    // 停止服务
    private static void StopService(string serviceName)
    {
        using (ServiceController service = new ServiceController(serviceName))
        {
            if (service.CanStop && service.Status != ServiceControllerStatus.Stopped)
            {
                service.Stop();
                service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(30));
                Console.WriteLine("服务已停止!");
            }
        }
    }
}