/// <summary>
/// 判断服务是否存在
/// </summary>
/// <param name="serviceName">服务名称</param>
/// <returns></returns>
private bool IsServiceExisted(string serviceName)
{
try
{
ServiceController[] services = ServiceController.GetServices();
foreach (ServiceController sc in services)
{
if (sc.ServiceName.ToLower() == serviceName.ToLower())
{
return true;
}
}
return false;
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// 安装服务
/// </summary>
/// <param name="serviceFilePath">服务程序所在路径</param>
private void InstallService(string serviceFilePath)
{
try
{
using (AssemblyInstaller installer = new AssemblyInstaller())
{
installer.UseNewContext = true;
installer.Path = serviceFilePath;
IDictionary savedState = new Hashtable();
installer.Install(savedState);
installer.Commit(savedState);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + " " + ex.StackTrace);
}
}
/// <summary>
/// 卸载服务
/// </summary>
/// <param name="serviceFilePath">服务程序所在路径</param>
private void UninstallService(string serviceFilePath)
{
try
{
using (AssemblyInstaller installer = new AssemblyInstaller())
{
installer.UseNewContext = true;
installer.Path = serviceFilePath;
installer.Uninstall(null);
}
}
catch (Exception ex)
{
}
}
/// <summary>
/// 启动服务
/// </summary>
/// <param name="serviceName">服务名称</param>
private void ServiceStart(string serviceName)
{
try
{
using (ServiceController control = new ServiceController(serviceName))
{
if (control.Status == ServiceControllerStatus.Stopped)
{
control.Start();
}
}
}
catch (Exception ex)
{
}
}
/// <summary>
/// 停止服务
/// </summary>
/// <param name="serviceName">服务名称</param>
private void ServiceStop(string serviceName)
{
try
{
using (ServiceController control = new ServiceController(serviceName))
{
if (control.Status == ServiceControllerStatus.Running)
{
control.Stop();
}
}
}
catch (Exception ex)
{
}
}
C# 启动 安装Windows服务 封装方法
于 2023-10-11 16:35:38 首次发布