C#通过SC命令和静态公共类来操作Windows服务
调用的Windows服务应用程序网址:http://www.cnblogs.com/pingming/p/5115304.html
一、引用

二、公共静态类:可以单独放到类库里
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration.Install;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using Microsoft.Win32; namespace CM.Web.UI
{
public static class WindowsServiceHelper
{
#region 已封装Window服务 /// <summary>
/// 安装服务
/// </summary>
/// <param name="NameService">Windows服务显示名称</param>
/// <returns>存在返回 true,否则返回 false;</returns>
public static bool InstallService(string serviceName)
{
bool flag = true;
if (!IsServiceIsExisted(serviceName))
{
try
{
string location = System.Reflection.Assembly.GetExecutingAssembly().Location;
string serviceFileName = location.Substring(, location.LastIndexOf('\\') + ) + serviceName + ".exe"; //测试用的绝对路径
//string serviceFileName = @"F:\CM.WebSite\KJLMDemo\bin\Debug\KJLMDemo.exe";
InstallMyService(null, serviceFileName);
}
catch
{
flag = false;
} }
return flag;
} /// <summary>
/// 卸载服务
/// </summary>
/// <param name="NameService">Windows服务显示名称</param>
/// <returns>存在返回 true,否则返回 false;</returns>
public static bool UninstallService(string serviceName)
{
bool flag = true;
if (IsServiceIsExisted(serviceName))
{
try
{
string location = System.Reflection.Assembly.GetExecutingAssembly().Location;
string serviceFileName = location.Substring(, location.LastIndexOf('\\') + ) + serviceName + ".exe";
//测试用的绝对路径
//string serviceFileName = @"F:\CM.WebSite\KJLMDemo\bin\Debug\KJLMDemo.exe";
UnInstallMyService(serviceFileName);
}
catch
{
flag = false;
}
}
return flag;
} /// <summary>
/// 检查Windows服务是否存在
/// </summary>
/// <param name="NameService">Windows服务显示名称</param>
/// <returns>存在返回 true,否则返回 false;</returns>
public static bool IsServiceIsExisted(string serviceName)
{
ServiceController[] services = ServiceController.GetServices();
foreach (ServiceController s in services)
{
if (s.ServiceName.ToLower() == serviceName.ToLower())
{
return true;
}
}
return false;
} /// <summary>
/// 安装Windows服务
/// </summary>
/// <param name="stateSaver">集合</param>
/// <param name="filepath">Windows服务程序文件路径</param>
private static void InstallMyService(IDictionary stateSaver, string filePath)
{
AssemblyInstaller AssemblyInstaller1 = new AssemblyInstaller();
AssemblyInstaller1.UseNewContext = true;
AssemblyInstaller1.Path = filePath;
AssemblyInstaller1.Install(stateSaver);
AssemblyInstaller1.Commit(stateSaver);
AssemblyInstaller1.Dispose();
} /// <summary>
/// 卸载Windows服务
/// </summary>
/// <param name="filePath">Windows服务程序文件路径</param>
private static void UnInstallMyService(string filePath)
{
AssemblyInstaller AssemblyInstaller1 = new AssemblyInstaller();
AssemblyInstaller1.UseNewContext = true;
AssemblyInstaller1.Path = filePath;
AssemblyInstaller1.Uninstall(null);
AssemblyInstaller1.Dispose();
} /// <summary>
/// 判断某个Windows服务是否启动
/// </summary>
/// <param name="serviceName">Windows服务显示名称</param>
/// <returns>bool</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);
}
} /// <summary>
/// 修改服务的启动项 2为自动,3为手动
/// </summary>
/// <param name="startType">2为自动,3为手动</param>
/// <param name="serviceName">Windows服务显示名称</param>
/// <returns>bool</returns>
public static bool ChangeServiceStartType(int startType, string serviceName)
{
try
{
RegistryKey regist = Registry.LocalMachine;
RegistryKey sysReg = regist.OpenSubKey("SYSTEM");
RegistryKey currentControlSet = sysReg.OpenSubKey("CurrentControlSet");
RegistryKey services = currentControlSet.OpenSubKey("Services");
RegistryKey servicesName = services.OpenSubKey(serviceName, true);
servicesName.SetValue("Start", startType);
}
catch (Exception ex)
{
return false;
}
return true; } /// <summary>
/// 启动服务
/// </summary>
/// <param name="serviceName">Windows服务显示名称</param>
/// <returns>bool</returns>
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 = ; i < ; i++)
{
service.Refresh();
System.Threading.Thread.Sleep();
if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running)
{
break;
}
if (i == )
{
flag = false;
}
}
}
}
return flag;
} /// <summary>
/// 停止服务
/// </summary>
/// <param name="serviceName">Windows服务显示名称</param>
/// <returns>bool</returns>
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 = ; i < ; i++)
{
service.Refresh();
System.Threading.Thread.Sleep();
if (service.Status == System.ServiceProcess.ServiceControllerStatus.Stopped)
{
break;
}
if (i == )
{
flag = false;
}
}
}
}
return flag;
}
#endregion
}
}
三、静态公共类操作Windows服务-------控制台程序
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration.Install;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32; namespace ConsoleService
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Window服务应用程序");
Console.WriteLine("请选择,[1]安装服务 [2]卸载服务 [3]启动服务 [4]关闭服务 [5]暂停/继续 [6]检测服务");
var rs = int.Parse(Console.ReadLine()); //一、通过封装类操作Windows服务
switch (rs)
{
case ://安装服务
InstallService("ServiceDemo");
Console.WriteLine("安装成功"); break;
case ://卸载服务
UninstallService("ServiceDemo");
Console.WriteLine("卸载成功");
break;
case ://启动服务
StartService("ServiceDemo");
Console.WriteLine("启动服务成功");
break;
case ://关闭服务
StopService("ServiceDemo");
Console.WriteLine("关闭服务成功");
break;
case ://暂停/继续
ServiceController serviceControllerPauseToContinue = new ServiceController("KJLMDemo");
if (serviceControllerPauseToContinue.CanPauseAndContinue)
{
if (serviceControllerPauseToContinue.Status == ServiceControllerStatus.Running)
serviceControllerPauseToContinue.Pause();
else if (serviceControllerPauseToContinue.Status == ServiceControllerStatus.Paused)
serviceControllerPauseToContinue.Continue();
}
break;
case ://判断服务是否开启 Console.WriteLine("服务状态:" + IsServiceStart("ServiceDemo"));
break;
default:
break;
}
Console.ReadKey();
}
}
}
四、通过SC命令操作Windows服务-------控制台程序
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration.Install;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32; namespace ConsoleService
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Window服务应用程序");
Console.WriteLine("请选择,[1]安装服务 [2]卸载服务 [3]启动服务 [4]关闭服务 [5]暂停/继续 [6]检测服务");
var rs = int.Parse(Console.ReadLine());
//二、通过SC命令操作Windows服务
switch (rs)
{
case ://安装服务
//取当前服务的路径bin/debug下面的exe文件
string path = @"F:\CM.WebSite\KJLMDemo\bin\Debug\KJLMDemo.exe";
Process.Start("sc", "create KJLMDemo binPath= \"" + path + "\" ");
Console.WriteLine("安装成功"); break;
case ://卸载服务
Process.Start("sc", "delete KJLMDemo");
Console.WriteLine("卸载成功");
break;
case ://启动服务
ServiceController serviceControllerStart = new ServiceController("KJLMDemo");
serviceControllerStart.Start();
Console.WriteLine("启动服务成功");
break;
case ://关闭服务
ServiceController serviceControllerStop = new ServiceController("KJLMDemo");
serviceControllerStop.Stop();
Console.WriteLine("关闭服务成功");
break;
case ://暂停/继续
ServiceController serviceControllerPauseToContinue = new ServiceController("KJLMDemo");
if (serviceControllerPauseToContinue.CanPauseAndContinue)
{
if (serviceControllerPauseToContinue.Status == ServiceControllerStatus.Running)
serviceControllerPauseToContinue.Pause();
else if (serviceControllerPauseToContinue.Status == ServiceControllerStatus.Paused)
serviceControllerPauseToContinue.Continue();
}
break;
case ://判断服务是否开启
ServiceController serviceControllerIsEnabled = new ServiceController("KJLMDemo");
string Status = serviceControllerIsEnabled.Status.ToString();
Console.WriteLine("服务状态:"+Status);
break;
default:
break;
}
}
}
C#通过SC命令和静态公共类来操作Windows服务的更多相关文章
- cmd命令行和bat批处理操作windows服务(转载)
一.cmd命令行---进行Windows服务操作 1.安装服务 sc create 服务名 binPath= "C:\Users\Administrator\Desktop\win32srv ...
- SC命令---安装、开启、配置、关闭 cmd命令行和bat批处理操作windows服务
一.cmd命令行---进行Windows服务操作 1.安装服务 sc create 服务名 binPath= "C:\Users\Administrator\Desktop\win32s ...
- 通过cmd 使用 InstallUtil.exe 命令 操作 windows服务 Windows Service
要安装windows service 首先要找到 InstallUtil.exe,InstallUtil.exe位置在 C:\Windows\Microsoft.NET\Framework\v4.0. ...
- 使用SC命令时注意事项
使用SC命令时注意事项[转] Windows 2003 Server存在一个sc命令,(好像Windows 2000/XP/NT都有这个.)该命令可以手工创建Windows服务(NT Service) ...
- 使用SC命令操作(安装、开启、配置、关闭、删除)Windows下的服务
目录 一.直接使用cmd命令行操作windows服务 二.使用bat批处理-操作windows服务 一.直接使用cmd命令行操作windows服务 1.安装服务 sc create 服务名 binPa ...
- 玩转Windows服务系列——命令行管理Windows服务
说到Windows服务的管理就不得不说通过命令行的方式管理Windows服务,因为无论是系统管理员,还是通过编程的方式调用cmd命令,命令行都是非常方便以及强大的工具. 接下来就看一下如何通过cmd命 ...
- 玩转Windows服务系列——命令行管理Windows服务
原文:玩转Windows服务系列——命令行管理Windows服务 说到Windows服务的管理就不得不说通过命令行的方式管理Windows服务,因为无论是系统管理员,还是通过编程的方式调用cmd命令, ...
- [转]玩转Windows服务系列——命令行管理Windows服务
本文转自:http://www.cnblogs.com/hbccdf/p/managewindowsservicewithcmd.html 说到Windows服务的管理就不得不说通过命令行的方式管理W ...
- java基础课程笔记 static 主函数 静态工具类 classpath java文档注释 静态代码块 对象初始化过程 设计模式 继承 子父类中的函数 继承中的构造函数 对象转型 多态 封装 抽象类 final 接口 包 jar包
Static那些事儿 Static关键字 被static修饰的变量成为静态变量(类变量) 作用:是一个修饰符,用于修饰成员(成员变量,成员方法) 1.被static修饰后的成员变量只有一份 2.当成员 ...
随机推荐
- python学习——面向对象的三大特性
一.继承 继承是一种创建新类的方式,在python中,新建的类可以继承一个或多个父类,父类又可称为基类或超类,新建的类称为派生类或子类. 1.python中类的继承分为:单继承和多继承 class P ...
- python教程(一)·命令行基本操作
先来了解下 "命令提示符". 等等?!既然本篇文章标题是"命令行基本操作",那怎么又说到"命令提示符"去了呢?客官莫要急,且听我说 命令提示 ...
- STM32 USB设备描述符、配置描述符、端点描述符含义
查了一整天的资料,自己把不懂的全部试了一遍 一下是程序以及注释 /* USB设备描述符*/ const uint8_t CustomHID_DeviceDescriptor[CUSTOMHID_SIZ ...
- Scala学习笔记(五)—— 元组和集合
1. 映射 映射Java中的Map,即Key/Value的数据形式 映射的创建,有以下两种方法 scala> val map =Map("Lisa" -> 90 , & ...
- R语言爬虫:CSS方法与XPath方法对比(代码实现)
CSS选择器和XPath方法都是用来定位DOM树的标签,只不过两者的定位表示形式上存在一些差别: CSS 方法提取节点 library("rvest") single_table_ ...
- chapter1
任何语言的开篇,想要学下去肯定要搞环境啦,下面我们就开始. 安装Kali Linux 虚拟机 首先进入kali的官网https://www.kali.org/downloads/,因为是新手,因此建议 ...
- 引用ZXing生成二维码
1.生成二维码 ZXing是一个开放源码的,用Java实现的多种格式的1D/2D条码图像处理库,它包含了联系到其他语言的端口. Zxing可以实现使用手机的内置的摄像头完成条形码的扫描及解码.本文引用 ...
- struts2-01:作用域传值
方式一.使用ServletActionContext(耦合度高,不建议使用) public String login(){ ServletActionContext.getRequest().getS ...
- C++中的引用常见用法
1.引用的内涵 引用就是给变量取外号而已. 2.四种不能使用引用的情况 void &r=x; //不能建立void类型引用 int &&r=x; //不能建立引用的引用 int ...
- getSteam
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using Sy ...