C# Window Service安装、卸载、恢复选项操作
using System;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
namespace ScmWrapper
{
public class ServiceHandler
{
#region 安装服务
/// <summary>
/// 安装服务
/// </summary>
public static bool InstallService(string nameService, string serviceFileName)
{
bool flag = true;
if (!IsServiceIsExisted(nameService))
{
try
{
using (Process myPro = new Process())
{
myPro.StartInfo.FileName = "cmd.exe";
myPro.StartInfo.UseShellExecute = false;
myPro.StartInfo.RedirectStandardInput = true;
myPro.StartInfo.RedirectStandardOutput = true;
myPro.StartInfo.RedirectStandardError = true;
myPro.StartInfo.CreateNoWindow = true;
myPro.Start();
//如果调用程序路径中有空格时,cmd命令执行失败,可以用双引号括起来 ,在这里两个引号表示一个引号(转义)
string str = $"{serviceFileName} install &exit";
myPro.StandardInput.WriteLine(str);
myPro.StandardInput.AutoFlush = true;
myPro.WaitForExit();
}
}
catch
{
flag = false;
}
//try
//{
// InstallmyService(null, serviceFileName);
//}
//catch (Exception ex)
//{
// flag = false;
//}
}
return flag;
}
#endregion
#region 卸载服务
/// <summary>
/// 卸载服务
/// </summary>
public static bool UninstallService(string nameService, string serviceFileName)
{
bool flag = true;
if (IsServiceIsExisted(nameService))
{
if (IsServiceStart(nameService))
{
StopService(nameService);
}
try
{
using (Process myPro = new Process())
{
myPro.StartInfo.FileName = "cmd.exe";
myPro.StartInfo.UseShellExecute = false;
myPro.StartInfo.RedirectStandardInput = true;
myPro.StartInfo.RedirectStandardOutput = true;
myPro.StartInfo.RedirectStandardError = true;
myPro.StartInfo.CreateNoWindow = true;
myPro.Start();
//如果调用程序路径中有空格时,cmd命令执行失败,可以用双引号括起来 ,在这里两个引号表示一个引号(转义)
string str = $"{serviceFileName} uninstall &exit";
myPro.StandardInput.WriteLine(str);
myPro.StandardInput.AutoFlush = true;
myPro.WaitForExit();
}
}
catch
{
flag = false;
}
//try
//{
// UnInstallmyService(serviceFileName);
//}
//catch
//{
// flag = false;
//}
}
return flag;
}
#endregion
#region 检查服务存在的存在性
/// <summary>
/// 检查服务存在的存在性
/// </summary>
/// <param name=" NameService ">服务名</param>
/// <returns>存在返回 true,否则返回 false;</returns>
public static bool IsServiceIsExisted(string serviceName)
{
ServiceController[] services = ServiceController.GetServices();
bool exist = services.Where(n => n.ServiceName.Equals(serviceName, StringComparison.OrdinalIgnoreCase))?.Count() > 0;
services = null;
return exist;
}
#endregion
#region 判断window服务是否启动
/// <summary>
/// 判断某个Windows服务是否启动
/// </summary>
/// <returns></returns>
public static bool IsServiceStart(string serviceName)
{
ServiceController psc = new ServiceController(serviceName);
bool bStartStatus = false;
try
{
if (!psc.Status.Equals(ServiceControllerStatus.Stopped))
{
bStartStatus = true;
}
return bStartStatus;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
psc.Close();
psc.Dispose();
}
}
#endregion
#region 修改服务的启动项
public static void SetRecoveryOptions(string serviceName)
{
try
{
using (Process myPro = new Process())
{
myPro.StartInfo.FileName = "cmd.exe";
myPro.StartInfo.UseShellExecute = false;
myPro.StartInfo.RedirectStandardInput = true;
myPro.StartInfo.RedirectStandardOutput = true;
myPro.StartInfo.RedirectStandardError = true;
myPro.StartInfo.CreateNoWindow = true;
myPro.Start();
//如果调用程序路径中有空格时,cmd命令执行失败,可以用双引号括起来 ,在这里两个引号表示一个引号(转义)
string str = $"sc failure {serviceName} reset=0 actions=restart/20000/restart/20000/restart/60000 &exit";//第一、二次失败20秒后重启服务
,后续失败60秒后重启服务
myPro.StandardInput.WriteLine(str);
myPro.StandardInput.AutoFlush = true;
myPro.WaitForExit();
}
}
catch
{
}
}
#endregion
#region 启动服务
public static bool StartService(string serviceName)
{
bool flag = true;
if (IsServiceIsExisted(serviceName))
{
System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName);
if (service.Status != System.ServiceProcess.ServiceControllerStatus.Running && service.Status != System.ServiceProcess.ServiceControllerStatus.StartPending)
{
service.Start();
for (int i = 0; i < 60; i++)
{
service.Refresh();
System.Threading.Thread.Sleep(1000);
if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running)
{
break;
}
if (i == 59)
{
flag = false;
}
}
}
service.Close();
service.Dispose();
}
return flag;
}
#endregion
#region 停止服务
public static bool StopService(string serviceName)
{
bool flag = true;
if (IsServiceIsExisted(serviceName))
{
System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName);
if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running)
{
service.Stop();
for (int i = 0; i < 60; i++)
{
service.Refresh();
System.Threading.Thread.Sleep(1000);
if (service.Status == System.ServiceProcess.ServiceControllerStatus.Stopped)
{
break;
}
if (i == 59)
{
flag = false;
}
}
}
service.Close();
service.Dispose();
}
return flag;
}
#endregion
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
2017-04-17 Mongodb $in $or 性能比较