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("服務已停止!");
}
}
}
}