System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController("FaceService");
if (service.Status == ServiceControllerStatus.Running)
{
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped);
}
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running);
//FaceService是服务的名字
补充记录:
/// <summary>
/// 卸载Windows服务
/// </summary>
/// <param name="filepath">程序文件路径</param>
public static void UnInstallmyService(string filepath)
{
try
{
AssemblyInstaller AssemblyInstaller1 = new AssemblyInstaller();
AssemblyInstaller1.UseNewContext = true;
AssemblyInstaller1.Path = filepath;
AssemblyInstaller1.Uninstall(null);
AssemblyInstaller1.Dispose();
}
catch (Exception e)
{
LOG.Logs.PutLog("卸载Windows服务时:" + e.Message);
}
}
/// <summary>
/// 安装Windows服务
/// </summary>
/// <param name="stateSaver">集合</param>
/// <param name="filepath">程序文件路径</param>
public static void InstallmyService(IDictionary stateSaver, string filepath)
{
try
{
AssemblyInstaller AssemblyInstaller1 = new AssemblyInstaller
{
UseNewContext = true,
Path = filepath
};
AssemblyInstaller1.Install(stateSaver);
AssemblyInstaller1.Commit(stateSaver);
AssemblyInstaller1.Dispose();
}
catch (Exception e)
{
LOG.Logs.PutLog("安装Windows服务时:" + e.Message);
}
}
/// <summary>
/// 检查服务存在的存在性
/// </summary>
/// <param name=" NameService ">服务名</param>
/// <returns>存在返回 true,否则返回 false;</returns>
public static bool IsServiceExisted(string NameService)
{
try
{
ServiceController[] services = ServiceController.GetServices();
foreach (ServiceController s in services)
{
if (s.ServiceName.ToLower() == NameService.ToLower())
{
return true;
}
}
}
catch (Exception e)
{
LOG.Logs.PutLog("IsServiceExisted时:" + e.Message);
}
return false;
}
/// <summary>
/// 启动服务
/// </summary>
/// <param name="serviceName">服务名字</param>
public static void ServiceStart(string serviceName)
{
try
{
if (IsServiceExisted(serviceName))//如果服务存在
{
using (ServiceController control = new ServiceController(serviceName))
{
if (control.Status == ServiceControllerStatus.Stopped)
{
control.Start();//开启被停止的服务
}
}
}
}
catch (Exception e)
{
LOG.Logs.PutLog("启动服务时" + e.Message);
}
}