主要宗旨:不已命令形式操作windows服务
static void Main(string[] args)
{
var path = @"E:\开发辅助项目\WCF\WCF.Test\WCF.Test\bin\Debug\WCF.Test.exe";
var serviceName = "WCF_TestService";
HandleService hs = new HandleService();
//启动服务
hs.StartService(serviceName);
//停止服务
hs.StopService(serviceName);
//卸载服务
hs.DeleteService(path);
//安装服务
hs.InstallService(path);
Console.ReadKey();
}
操作类
public class HandleService
{
/// <summary>
/// 获取服务
/// </summary>
/// <param name="serviceName">服务名</param>
/// <returns></returns>
public ServiceController GetService(string serviceName)
{
try
{
//可以获取所有的服务
//ServiceController[] service = ServiceController.GetServices();
//无法打开计算上的服务控制管理器。
//ServiceController[] service = ServiceController.GetServices(serviceName);
//if (service.Length <= 0) return null;
ServiceController service = new ServiceController(serviceName);
return service;
}
catch (Exception ex)
{
return null;
}
}
/// <summary>
/// 安装服务
/// </summary>
/// <param name="path">路径</param>
public void InstallService(string path)
{
try
{
AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller();
myAssemblyInstaller.UseNewContext = true;
myAssemblyInstaller.Path = path;
myAssemblyInstaller.Install(null);
myAssemblyInstaller.Commit(null);
myAssemblyInstaller.Dispose();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.Read();
}
/// <summary>
/// 启动服务
/// </summary>
/// <param name="serviceName">服务名</param>
public void StartService(string serviceName)
{
try
{
var service = GetService(serviceName);
if (service == null)
{
Console.Write($"windows上不存在{serviceName}服务!");
return;
}
if (service.Status == ServiceControllerStatus.Paused ||
service.Status == ServiceControllerStatus.Stopped)
{
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 30));
}
Console.WriteLine($"{serviceName}已经启动");
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// 停止服务
/// </summary>
/// <param name="serviceName">服务名</param>
public void StopService(string serviceName)
{
try
{
var service = GetService(serviceName);
if (service == null)
{
Console.Write($"windows上不存在{serviceName}服务!");
return;
}
if (service.Status == ServiceControllerStatus.Running ||
service.Status == ServiceControllerStatus.PausePending || service.Status == ServiceControllerStatus.StartPending)
{
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 30));
}
Console.WriteLine($"{serviceName}已经停止");
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// 卸载服务
/// </summary>
/// <param name="path"></param>
public void DeleteService(string path)
{
try
{
AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller();
myAssemblyInstaller.UseNewContext = true;
myAssemblyInstaller.Path = path;
myAssemblyInstaller.Uninstall(null);
myAssemblyInstaller.Dispose();
Console.WriteLine("卸载服务成功!");
}
catch (Exception ex)
{
Console.WriteLine("卸载服务失败");
}
}
}