调用的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服务的更多相关文章

  1. cmd命令行和bat批处理操作windows服务(转载)

    一.cmd命令行---进行Windows服务操作 1.安装服务 sc create 服务名 binPath= "C:\Users\Administrator\Desktop\win32srv ...

  2. SC命令---安装、开启、配置、关闭 cmd命令行和bat批处理操作windows服务

      一.cmd命令行---进行Windows服务操作 1.安装服务 sc create 服务名 binPath= "C:\Users\Administrator\Desktop\win32s ...

  3. 通过cmd 使用 InstallUtil.exe 命令 操作 windows服务 Windows Service

    要安装windows service 首先要找到 InstallUtil.exe,InstallUtil.exe位置在 C:\Windows\Microsoft.NET\Framework\v4.0. ...

  4. 使用SC命令时注意事项

    使用SC命令时注意事项[转] Windows 2003 Server存在一个sc命令,(好像Windows 2000/XP/NT都有这个.)该命令可以手工创建Windows服务(NT Service) ...

  5. 使用SC命令操作(安装、开启、配置、关闭、删除)Windows下的服务

    目录 一.直接使用cmd命令行操作windows服务 二.使用bat批处理-操作windows服务 一.直接使用cmd命令行操作windows服务 1.安装服务 sc create 服务名 binPa ...

  6. 玩转Windows服务系列——命令行管理Windows服务

    说到Windows服务的管理就不得不说通过命令行的方式管理Windows服务,因为无论是系统管理员,还是通过编程的方式调用cmd命令,命令行都是非常方便以及强大的工具. 接下来就看一下如何通过cmd命 ...

  7. 玩转Windows服务系列——命令行管理Windows服务

    原文:玩转Windows服务系列——命令行管理Windows服务 说到Windows服务的管理就不得不说通过命令行的方式管理Windows服务,因为无论是系统管理员,还是通过编程的方式调用cmd命令, ...

  8. [转]玩转Windows服务系列——命令行管理Windows服务

    本文转自:http://www.cnblogs.com/hbccdf/p/managewindowsservicewithcmd.html 说到Windows服务的管理就不得不说通过命令行的方式管理W ...

  9. java基础课程笔记 static 主函数 静态工具类 classpath java文档注释 静态代码块 对象初始化过程 设计模式 继承 子父类中的函数 继承中的构造函数 对象转型 多态 封装 抽象类 final 接口 包 jar包

    Static那些事儿 Static关键字 被static修饰的变量成为静态变量(类变量) 作用:是一个修饰符,用于修饰成员(成员变量,成员方法) 1.被static修饰后的成员变量只有一份 2.当成员 ...

随机推荐

  1. python3 安装pyhanlp方法

    直接pip install pyhanlp的时候会提示缺少Microsoft Visual c++环境, 其实没有Microsoft Visual c++环境也是可以的, 可以先安装jpype1,然后 ...

  2. CentOS6升级Python2.6到3.7,错误处理[No module named '_ctypes']

    CentOS6升级Python2.6到3.7,错误处理[No module named '_ctypes'] 因开发需要,在CentOS 6 服务器将Python2进行升级到Python3.由于工作中 ...

  3. 解决protobuf import路径的问题

    网上关于protobuf import的文章不太详细,有些问题说的不全,比如import时的路径是在哪个目录中搜索的,比如: 我有一个这样的目录结构,我怎么在demo2/protoDemo2.prot ...

  4. Unicode编码相关概念

    1.Unicode是一种字符映射方案,这种映射并不是编码(即还没有到二进制机器码层面),而是像一个电话本一样,把全世界所有语言使用的字符,都映射成一个"u+"开头的数字(在JAVA ...

  5. 基于套接字通信的简单练习(FTP)

    本项目基于c/s架构开发(采用套接字通信,使用TCP协议) FTP-Socket"""__author:rianley cheng""" 功 ...

  6. sphinx生成cakephp文档

    cakephp的文档是用一个叫sphinx程序生成的 这个程序是python写的,所以我们要用sphinx本机必须先装python. 编译过程在Ubuntu下进行,默认Ubuntu已经安装了pytho ...

  7. 离线安装Sharepoint工具

    1. 首先安装操作系统,Windows Server 2008 R2,可以是企业版,也可以是数据中心版.然后再安装上SP1. 2. 在"服务管理"里面,添加角色,安装IIS.    ...

  8. 探索 Flask

    探索 Flask 探索 Flask 是一本关于使用 Flask 开发 Web 应用程序的最佳实践和模式的书籍.这本书是由 426 名赞助人 在 Kickstarter 上 于 2013 年 7 月资助 ...

  9. 从golang的垃圾回收说起(上篇)

    本文来自网易云社区 1 垃圾回收中的重要概念 1.1 定义 In computer science, garbage collection (GC) is a form of automatic me ...

  10. 前台时间格式 2019-03-09T16:00:00.000Z

    问题描述: 本想在前台把字符串格式的日期(2019-03-09)转换成日期格式(2019-03-09 00:00:00),但当把这个参数传到后台去后却变成了2019-03-08T16:00:00.00 ...