- 判断Window服务是否存在
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public static bool ServiceIsExisted(string serviceName) { ServiceController[] servicesController = ServiceController.GetServices(); foreach (ServiceController each in servicesController) { if (each.ServiceName.ToLower().Trim() == serviceName.ToLower().Trim()) return true; } return false; }
2.启动服务
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public static bool StartService(string serviceName) { try { ServiceController serviceController = new ServiceController(serviceName); if (serviceController.Status == ServiceControllerStatus.Running) { return true; } else { TimeSpan timeout = TimeSpan.FromMilliseconds(1000 * 10); serviceController.Start(); serviceController.WaitForStatus(ServiceControllerStatus.Running, timeout); } } catch { return false; } return true; }
3.停止服务
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public static bool StopService(string serviceName) { try { ServiceController serviceController = new ServiceController(serviceName); if (serviceController.Status == ServiceControllerStatus.Stopped) return true; else { TimeSpan timeout = TimeSpan.FromMilliseconds(1000 * 10); serviceController.Stop(); serviceController.WaitForStatus(ServiceControllerStatus.Stopped, timeout); } } catch { return false; } return true; }
4.获取服务的状态
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public static ServiceControllerStatus GetServiceStatus(string serviceName) { try { ServiceController serviceController = new ServiceController(serviceName); return serviceController.Status; } catch { return ServiceControllerStatus.Stopped; } }
5. 获取服务的启动类型
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public static string GetServiceStartType(string serviceName) { try { RegistryKey registryKey = Registry.LocalMachine; RegistryKey sysRegistryKey = registryKey.OpenSubKey("SYSTEM"); RegistryKey currentControlSet = sysRegistryKey.OpenSubKey("CurrentControlSet"); RegistryKey services = currentControlSet.OpenSubKey("Services"); RegistryKey servicesName = services.OpenSubKey(serviceName, true); return servicesName.GetValue("Start").ToString(); } catch (Exception ex) { return string.Empty; } }
6.设置服务的启动类型
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//修改服务的启动项 2为自动,3为手动 public static bool SetServiceStartType(int startType, string serviceName) { try { RegistryKey registryKey = Registry.LocalMachine; RegistryKey sysRegistryKey = registryKey.OpenSubKey("SYSTEM"); RegistryKey currentControlSet = sysRegistryKey.OpenSubKey("CurrentControlSet"); RegistryKey services = currentControlSet.OpenSubKey("Services"); RegistryKey servicesName = services.OpenSubKey(serviceName, true); servicesName.SetValue("Start",startType); } catch (Exception ex) { return false; } return true; }