做项目需要对Windows服务进行操作,从网上找了一些资料,总结如下:

(以下程序在程序中测试通过)

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Configuration.Install;
using System.Collections.Specialized;
using System.ServiceProcess; namespace IAU.ServerInstall.BLL
{
public class ServiceControl
{
/// <summary>
/// 注册服务(注册完就启动,已经存在的服务直接启动。)
/// </summary>
/// <param name="strServiceName">服务名称</param>
/// <param name="strServiceInstallPath">服务安装程序完整路径(.exe程序完整路径)</param>
public void Register(string strServiceName, string strServiceInstallPath)
{
IDictionary mySavedState = new Hashtable(); try
{
System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(strServiceName); //服务已经存在则卸载
if (ServiceIsExisted(strServiceName))
{
//StopService(strServiceName);
UnInstallService(strServiceName, strServiceInstallPath);
}
service.Refresh();
//注册服务 http://www.cnblogs.com/sosoft/
AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller(); mySavedState.Clear();
myAssemblyInstaller.Path = strServiceInstallPath;
myAssemblyInstaller.UseNewContext = true;
myAssemblyInstaller.Install(mySavedState);
myAssemblyInstaller.Commit(mySavedState);
myAssemblyInstaller.Dispose(); service.Start();
}
catch (Exception ex)
{
throw new Exception("注册服务时出错:" + ex.Message);
}
} /// <summary>
/// 卸载服务
/// </summary>
/// <param name="strServiceName">服务名称</param>
/// <param name="strServiceInstallPath">服务安装程序完整路径(.exe程序完整路径)</param>
public void UnInstallService(string strServiceName, string strServiceInstallPath)
{
try
{
if (ServiceIsExisted(strServiceName))
{
//UnInstall Service
AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller();
myAssemblyInstaller.UseNewContext = true;
myAssemblyInstaller.Path = strServiceInstallPath;
myAssemblyInstaller.Uninstall(null);
myAssemblyInstaller.Dispose();
}
}
catch (Exception ex)
{
throw new Exception("卸载服务时出错:" + ex.Message);
}
} /// <summary>
/// 判断服务是否存在
/// </summary>
/// <param name="serviceName">服务名</param>
/// <returns></returns>
public bool ServiceIsExisted(string serviceName)
{
ServiceController[] services = ServiceController.GetServices();
foreach (ServiceController s in services)
{
if (s.ServiceName == serviceName)
{
return true;
}
}
return false;
} /// <summary>
/// 启动服务(启动存在的服务,30秒后启动失败报错)
/// </summary>
/// <param name="serviceName">服务名</param>
public void StartService(string serviceName)
{
if (ServiceIsExisted(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 == )
{
throw new Exception("服务" + serviceName + "启动失败!");
}
}
}
}
} /// <summary>
/// 停止服务(停止存在的服务,30秒后停止失败报错)
/// </summary>
/// <param name="serviceName"></param>
public void StopService(string serviceName)
{
if (ServiceIsExisted(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 == )
{
throw new Exception("服务" + serviceName + "停止失败!");
}
}
}
}
}
}
}

博客园 柔城  以上代码概述:

C#对Windows服务操作(注册安装服务,卸载服务,启动停止服务,判断服务存在)

C#开发Windows服务的基础代码的更多相关文章

  1. 使用Visual Studio 2015 Community 开发windows服务

    昨天研究在.NET下开发Windows服务程序,期间遇到一些小问题,这里仅将自己的开发过程和需要注意的地方写下和广大网友分享……  1.基础   Windows服务是指系统启动时能够自己运行的程序.W ...

  2. C#开发Windows服务 附简单实例实现禁止QQ运行

    本实例主要实现下面三个基本功能 1.C#开发windows服务 2.禁止QQ等程序运行 3.为windows服务创建自动安装程序 下面针对这三个基本功能进行实现 一.C#开发windows服务 Win ...

  3. VS2013开发Windows服务项目

    这篇随笔里,我将介绍如何用VS2013开发Windows服务项目,实现的功能是定时发送电子邮件. 开发环境:VS2013,SQL Server2008,采用C#语言开发 步骤一:创建Windows服务 ...

  4. C#开发Windows服务详细流程

    1.Windows服务简单介绍 Windows服务程序是在Windows操作系统下能完成特定功能的可执行的应用程序,主要用于长时间运行的功能或者执行定时任务.一般情况下,用户不能通过用户界面来安装和启 ...

  5. 使用Topshelf开发Windows服务、log4net记录日志

    开发windows服务,除了在vs里新建服务项目外(之前有写过具体开发方法,可点击查看),还可以使用Topshelf. 不过使用topshelf需要.netframework 4.5.2版本,在vs2 ...

  6. c#金额转换成中文大写金额 .Net开发Windows服务

    c#金额转换成中文大写金额   2018-08-24 转别人 c#金额转换成中文大写金额 /// <summary> /// 金额转换成中文大写金额 /// </summary> ...

  7. C# DateTime的11种构造函数 [Abp 源码分析]十五、自动审计记录 .Net 登陆的时候添加验证码 使用Topshelf开发Windows服务、记录日志 日常杂记——C#验证码 c#_生成图片式验证码 C# 利用SharpZipLib生成压缩包 Sql2012如何将远程服务器数据库及表、表结构、表数据导入本地数据库

    C# DateTime的11种构造函数   别的也不多说没直接贴代码 using System; using System.Collections.Generic; using System.Glob ...

  8. C#开发windows服务如何调试——资料整理

    原文标题:C# Windows服务程序如何进行调试 原文地址:https://jingyan.baidu.com/article/456c463b18e1b00a583144b3.html 第一种: ...

  9. C#常规开发Windows服务

    .Net平台下开发Windows服务的支持库很多,除了通过标准的Windows服务项目,还有一些优秀的开源架构比如:TopSelf:本文以常规项目为例 一.开发 1.新建[Windows服务] 项目: ...

随机推荐

  1. hash_map的简洁实现

    hash_map的简洁实现   hash_map是经常被使用的一种数据结构,而其实现方式也是多种多样.如果要求我们使用尽可能简单的方式实现hash_map,具体该如何做呢? 我们知道hash_map最 ...

  2. JavaBean和Map转换封装类

    package com.ljq.util; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans. ...

  3. 使用EntityFramework的烦恼

    我有一个应用程序,是实现数据ETL同步的,即把数据从一个db里抽取出来,经过处理后,存储到另一个db里. O/RM采用的是EF db First. 随着项目程序的开发,EF的不足越来越明显. ● 根据 ...

  4. Java-数组练习5

    5.从键盘上输入一个正整数n,请按照以下五行杨辉三角形的显示方式, 输出杨辉三角形的前n行.请采用循环控制语句来实现. (三角形腰上的数为1,其他位置的数为其上一行相邻两个数之和.) 1 1   1 ...

  5. 1027 HTML的初学

       HTML   是一种超文本标记语言内容(Hyper Text  Markup Language)    CSS       网页美化    Javascript    脚本语言(JS)    H ...

  6. Yii2框架RESTful API教程(一) - 快速入门

    前不久做一个项目,是用Yii2框架写一套RESTful风格的API,就去查了下<Yii 2.0 权威指南 >,发现上面写得比较简略.所以就在这里写一篇教程贴,希望帮助刚接触Yii2框架RE ...

  7. Jquery 选择器 详解

    在线文档地址:http://tool.oschina.net/apidocs/apidoc?api=jquery 各种在线工具地址:http://www.ostools.net/ 一.基本选择器 $( ...

  8. javascript_core_01之数据类型与运算

    1.数据类型转换: ①隐式转换:程序根据需要,自动转化数据类型: ②强制转换:主动调用函数执行转换: 2.字符串强制转换: ①x.toString():不能转换null和undefined: ②Str ...

  9. Excel学习笔记

    ---恢复内容开始--- -----------随学随记----------- 获取当前日期: 获取当前系统时间,包含年月日时分秒: =NOW() 获取当前系统时间,包含年月日: =TODAY() 只 ...

  10. JAVA-集合作业-已知有十六支男子足球队参加2008 北京奥运会。写一个程序,把这16 支球队随机分为4 个组。采用List集合和随机数

    第二题 已知有十六支男子足球队参加2008 北京奥运会.写一个程序,把这16 支球队随机分为4 个组.采用List集合和随机数 2008 北京奥运会男足参赛国家: 科特迪瓦,阿根廷,澳大利亚,塞尔维亚 ...