windows 服务的启动与安装
在使用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 服务的启动与安装的更多相关文章
- SpringBoot注册Windows服务和启动报错的原因
SpringBoot注册Windows服务和启动报错的原因 Windows系统启动Java程序会弹出黑窗口.黑窗口有几点不好.首先它不美观:其次容易误点导致程序关闭:但最让我匪夷所思的是:将鼠标光标选 ...
- 以Windows服务方式启动MySQL,并将其默认编码设置为UTF-8
系统环境:Windows XP Professional 版本 2002 Service Pack 3 // 第1步:创建选项文件.首先下载mysql-5.5.12-win32.zip,只需复制mys ...
- 如何检测指定的Windows服务是否启动
在项目中,特别是安装项目中我们经常要判断一些服务是否启动(判断SQL Server是否启动最常见),在.net中我们如何判断指定的Windows服务是否启动呢?首先要知道Windows服务的显示名称, ...
- Windows服务之启动、停止、暂停、继续
原文:Windows服务之启动.停止.暂停.继续 Windows服务之启动.停止.暂停.继续 2011-11-09 15:07:37 我来说两句 收藏 我要投稿 [字体:小 大] ...
- c#创建windows服务(代码方式安装、启动、停止、卸载服务)
转载于:https://www.cnblogs.com/mq0036/p/7875864.html 一.开发环境 操作系统:Windows 10 X64 开发环境:VS2015 编程语言:C# .NE ...
- gitblit无法安装windows服务或者启动服务失败:Failed creating java
gitblit解压后,命令行运行installService.cmd之前,需要修改里面的参数,将ARCH修改x86,默认是amd64,我的机器是windows 10 Pro 64位版本,jdk也都是6 ...
- C# windows服务制作(包括安装及卸载)
开篇语 因工作内容需要做一个windows服务,此前并没有相关经验,所以做了一个demo来跑跑这个梗(高手跳过,需要的来踩)- 效果如下:打开服务,可以找到我们新增的一个windows服务,这个dem ...
- windows服务的创建、安装、调试全过程及引发的后续学习
前几天做项目的时候需要用到window服务,研究一段时间,算是掌握了最基本的使用方法吧,现总结如下: 引言:在项目过程中碰到一个问题:需要不断的扫描一个大型数据库表,并获取dataset,以便做后续的 ...
- windows服务的创建、安装和调试
1.创建 windows服务 项目 文件 -> 新建项目 -> 已安装的模板 -> Visual C# -> windows ,在右侧窗口选择"windows 服 ...
随机推荐
- Python 数据排序和列表迭代和列表推导应用
1.In-place sorting 原地排序 data=[6,4,5,2,3,1] print ('before sort', data) data.sort() print ('after sor ...
- Linux下SSH的Log文件路径
Redhat or Fedora Core: /var/log/secure # Mandrake, FreeBSD or OpenBSD: /var/log/auth.log # SuSE: /va ...
- freeswitch编译
编译1.6版本的话,debian的包就太老,需要添加新源 echo "deb http://files.freeswitch.org/repo/deb/debian/ jessie main ...
- [terminal]Terminal常用快捷键
1. 终端操作 Ctrl+d/exit 退出当前Termina1 Ctrl+l/clear 清除屏幕 Ctrl+Alt+t/Ctrl+shift+n 打开新终端窗口 Ctrl+shift+ ...
- 黄聪:使用$.getJSON解决ajax跨域访问 JQuery 的跨域方法(服务器端为wordpress程序)
客户端: <input id="cat" name="cat" type="hidden" value="<? ech ...
- aptana studio 3 自动换行(无需插件)
菜单-Window-Preferences-Aptana Studio-Editors,勾选“Enable word wrap”,然后重启编辑器.
- Form_通过Zoom客制化跳转页面功能(案例)
2012-09-08 Created By BaoXinjian
- HTML 表单验证和事件
1.表单验证<form></form> (1).非空验证(去空格) (2).对比验证(跟一个值对比) (3).范围验证(根据一个范围进行判断) (4).固定格式验证:电话号码, ...
- AsyncTask的学习
具体的用法请看我之前的一篇随笔,用php+mysql+json实现用户反馈. AsyncTask的目标是为你的线程提供管理服务. AsyncTask的执行分为四个步骤,每一步都对应一个回调方法,这些方 ...
- 获取mysql数据表中的列名
select COLUMN_NAME from information_schema.columns where table_name='table_name' DESCRIBE table_name ...