在使用windows 操作系统时,我们对windows服务再也熟悉不过了,这些服务有的是系统层的,有的是应用层的,大部分都是运行在桌面的后台,可以在进程中看到,有时候在做web项目时,在站点启动时要启动相应的服务,比如报警之类的,下面主要介绍在C#程序中安装 启动 与停止服务的方法, 可通过两种方式来启动,一种是通过运行编写好的 bat 文件,另一种是通过程序直接安装启动服务,具体做法如下:

1. bat 文件来安装 启动 停止 服务

 首先将  bat 文件编写成以管理员的身份运行,在程序启动时,检测服务是否存在,如果不存在,就运行bat文件,安装服务,安装好后启动即可,如果服务已经存在,就要检测服务的状态,如果是停止,就要对服务进行启动.

 以管理员运行bat 文件安装并启动服务:

 

@Rem  InstallUtil service webapiservice under administrator permissions
@Rem created 2015-12-20
@Rem Author wisdo @All Rights Reserved @echo off
@echo place wait a minutes...
%1 %2
ver|find "5.">nul&&goto :mystart
mshta vbscript:createobject("shell.application").shellexecute("%~s0","goto :mystart","","runas",1)(window.close)&goto:exit
:mystart
%~d0
CD %~dp0
set %cd%="%windir%\system32"
InstallUtil wisdo.exe
net start wisdo
pause
:exit
exit

 相应的停止服务就是  net stop wisdo

相应的C#中运行 bat 文件的代码:

readonly string serviceName="wisdo";
readonly string sveFilePath = "/content/services/";
/// <summary>
/// 安装服务
/// </summary>
/// <param name="filePath">bat文件所在的目录</param>
    /// <param name="sveName">服务的名称</param>
private void InstallService(string filePath,string sveName)
{
filePath = System.Web.HttpContext.Current.Server.MapPath(filePath); // 当前请求的绝对路径
if (!IsExisted(sveName))
{
System.Diagnostics.Process pro = new System.Diagnostics.Process();
pro.StartInfo.WorkingDirectory = filePath;
pro.StartInfo.FileName = "wisdo.bat";
pro.StartInfo.CreateNoWindow = true;
pro.StartInfo.UseShellExecute = true;
pro.Start();
pro.WaitForExit();
}
else
{
StartService(sveName); //启动服务,同样是运行启动服务的 bat 文件,只要将安装服务的bat文件中的 InstallUtil wisdo.exe 改成 net start wisdo 即可
}
}

需要引入的命名空间名字: using System.Configuration.Install;

2. 以C#代码的方式来安装,启动,停止 卸载服务

 同样需要引入命名空间:  using System.ServiceProcess; 

 

        #region  webServiceAPI 服务启动与停止

        /// <summary>
/// 启动服务
/// </summary>
/// <param name="sveName">服务的名称</param>
private void StartService(string sveName)
{
try
{
ServiceController sveCtr = new ServiceController(sveName);
if (sveCtr.Status != ServiceControllerStatus.Running ||
sveCtr.Status != ServiceControllerStatus.StartPending)
{
sveCtr.Start();
}
}
catch (Exception)
{
//TODO: 日志记录
}
} /// <summary>
/// 停止服务
/// </summary>
/// <param name="name">服务名称</param>
private void StopService(string name)
{
try
{
ServiceController sveCtr = new ServiceController(name);
if (sveCtr.Status != ServiceControllerStatus.Stopped || sveCtr.Status
!= ServiceControllerStatus.StopPending)
{
sveCtr.Stop();
}
}
catch (Exception)
{
//TODO: 日志记录
}
} /// <summary>
/// 判断是否存在服务
/// </summary>
/// <param name="name">服务名称</param>
/// <returns></returns>
private bool IsExisted(string name)
{
try
{
//ServiceController srvCtrl = new ServiceController(name);
//ServiceControllerStatus scStatus = srvCtrl.Status;
//return true; ServiceController[] sctrs = ServiceController.GetServices();
foreach (ServiceController item in sctrs)
{
if (item.ServiceName.ToLower() == name.ToLower())
{
return true;
}
}
return false;
}
catch (Exception)
{
//TODO: 日志记录
return false;
}
} /// <summary>
/// 安装服务
/// </summary>
/// <param name="filePath"></param>
/// <param name="sveName"></param>
private void InstallService(string filePath,string sveName)
{
try{
filePath = sveFilePath + "wisdoService.exe";
filePath = System.Web.HttpContext.Current.Server.MapPath(filePath);
System.Collections.Hashtable hashState = new
System.Collections.Hashtable();
AssemblyInstaller asInst = new AssemblyInstaller();
asInst.UseNewContext = true;
asInst.Path =
System.Web.HttpContext.Current.Server.MapPath(filePath);
asInst.Install(hashState);
asInst.Commit(hashState);
//启动服务
StartService(sveName);
}
catch(Exception)
{
//TODO: 日志记录
}
} /// <summary>
/// 卸载服务
/// </summary>
/// <param name="filePath"></param>
/// <param name="sveName"></param>
private void UnInstallService(string filePath,string sveName)
{
filePath = sveFilePath + "UnwisdoService.exe";
if (IsExisted(sveName))
{
AssemblyInstaller asInst = new AssemblyInstaller();
asInst.UseNewContext = true;
asInst.Path = System.Web.HttpContext.Current.Server.MapPath(filePath);
asInst.Uninstall(null);
asInst.Dispose();
}
}
#endregion

但这里要注意一点: 会有权限的问题也就是说win7及以上版本的 windows 操作系统中,如果服务最被设计成系统层的服务,那么在这里通过C# 程序的方式来安装与启动时会涉及到权限的问题,虽然有对应的解决办法,但办法比较复杂,这里就会涉及到操作系统管理员的权限,如果能满足最小的需求,可以采用借助 bat 文件的方法来安装与启动服务.

参考文章:

http://www.cnblogs.com/therock/articles/2261371.html           解决vista和win7在windows服务中交互桌面权限问题:穿透Session 0 隔离

http://www.cnblogs.com/luxilin/p/3347212.html              C# window Service实现调用有UI的应用程序(关于win xp以后的window系统)

http://www.cnblogs.com/SunShineYPH/archive/2011/12/13/2285570.html            Bat命令学习

http://www.cnblogs.com/wisdo/p/5060346.html                                                              BAT文件命令

http://blog.chinaunix.net/uid-27000874-id-3224772.html               win7中以管理员身份运行bat脚本时,获取当前文件所在目录

  

windows 服务的启动与安装的更多相关文章

  1. SpringBoot注册Windows服务和启动报错的原因

    SpringBoot注册Windows服务和启动报错的原因 Windows系统启动Java程序会弹出黑窗口.黑窗口有几点不好.首先它不美观:其次容易误点导致程序关闭:但最让我匪夷所思的是:将鼠标光标选 ...

  2. 以Windows服务方式启动MySQL,并将其默认编码设置为UTF-8

    系统环境:Windows XP Professional 版本 2002 Service Pack 3 // 第1步:创建选项文件.首先下载mysql-5.5.12-win32.zip,只需复制mys ...

  3. 如何检测指定的Windows服务是否启动

    在项目中,特别是安装项目中我们经常要判断一些服务是否启动(判断SQL Server是否启动最常见),在.net中我们如何判断指定的Windows服务是否启动呢?首先要知道Windows服务的显示名称, ...

  4. Windows服务之启动、停止、暂停、继续

    原文:Windows服务之启动.停止.暂停.继续 Windows服务之启动.停止.暂停.继续 2011-11-09 15:07:37     我来说两句 收藏    我要投稿    [字体:小 大] ...

  5. c#创建windows服务(代码方式安装、启动、停止、卸载服务)

    转载于:https://www.cnblogs.com/mq0036/p/7875864.html 一.开发环境 操作系统:Windows 10 X64 开发环境:VS2015 编程语言:C# .NE ...

  6. gitblit无法安装windows服务或者启动服务失败:Failed creating java

    gitblit解压后,命令行运行installService.cmd之前,需要修改里面的参数,将ARCH修改x86,默认是amd64,我的机器是windows 10 Pro 64位版本,jdk也都是6 ...

  7. C# windows服务制作(包括安装及卸载)

    开篇语 因工作内容需要做一个windows服务,此前并没有相关经验,所以做了一个demo来跑跑这个梗(高手跳过,需要的来踩)- 效果如下:打开服务,可以找到我们新增的一个windows服务,这个dem ...

  8. windows服务的创建、安装、调试全过程及引发的后续学习

    前几天做项目的时候需要用到window服务,研究一段时间,算是掌握了最基本的使用方法吧,现总结如下: 引言:在项目过程中碰到一个问题:需要不断的扫描一个大型数据库表,并获取dataset,以便做后续的 ...

  9. windows服务的创建、安装和调试

    1.创建 windows服务 项目   文件 -> 新建项目 -> 已安装的模板 -> Visual C# -> windows ,在右侧窗口选择"windows 服 ...

随机推荐

  1. Python 处理多层嵌套列表

    >>> movies =[ "the holy grail", 1975,"terry jones",91, ["graham ch ...

  2. 【转】SQL SERVER 存储过程中变量的作用域

    今天遇到一个很有趣的事情,以前没有注意过,所以记下来. 先来看例子. SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE PROCEDURE ...

  3. 在UIViewController中获得Container View里的embed viewController的引用

    When you want to use a controller you use the UIStoryboard method instantiateViewControllerWithIdent ...

  4. CF 191C Fools and Roads lca 或者 树链剖分

    They say that Berland has exactly two problems, fools and roads. Besides, Berland has n cities, popu ...

  5. Python语言快速入门

    Python的主提示符(>>>):是解释器告诉你它正在等待你输入的下一个语句 Python的次提示符(...):告诉你解释器正在等待你输入当前语句的其他部分 [简介] Python( ...

  6. jsp的一些基本语法

    jsp页面内容 <%@ page language="java" import="java.util.*" pageEncoding="UTF- ...

  7. SyntaxError: Non-UTF-8 code starting with '\xba' in file 错误的解决方法!!

    第一次在Eclipse建立python工程,添加了自己新建的文件,写了一点代码,随后执行时候出现了错误,和昨天我在Visual Studio 2015里面一样,错误: SyntaxError: Non ...

  8. Android 2.3 NFC简介

    Android 2.3加入了NFC(近场通讯)的支持.官网developer.android.com的英文介绍如下:Near Field Communications (NFC)Android 2.3 ...

  9. 在Windows驗證網站設定部分匿名存取

    最近接連遇到幾次的需求:供內部使用的ASP.NET網站,全站使用Windows驗證,使用者以網域AD帳號登入,但網站包含少數API性質的ASHX.ASPX或MVC Action,提供其他系統呼叫整合. ...

  10. [Flex] ButtonBar系列——flex3 labelFunction用户提供的函数,在每个项目上运行以确定其标签

    <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="h ...