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 服 ...
随机推荐
- Windows2012 cannot access netapp CIFS share
NAS1> options cifs.smb2.signing.requiredcifs.smb2.signing.required off NAS1> options cifs.smb2 ...
- gridview例子
直接贴代码 MainActivity.java public class MainActivity extends AppCompatActivity { private GridView _grid ...
- Makefile选项CFLAGS,LDFLAGS,LIBS
CFLAGS 表示用于 C 编译器的选项, CXXFLAGS 表示用于 C++ 编译器的选项.这两个变量实际上涵盖了编译和汇编两个步骤. CFLAGS: 指定头文件(.h文件)的路径,如:CFLAGS ...
- netty常用代码
一. Server public class TimeServer_argu { public void bind(int port) throws InterruptedException { Ev ...
- linux 定时器编程实例(完善中).....
最近在写linux 下的定时器编程实验,测试发现 usleep函数在 x86 架构下的定时还是比较准确的,在arm9下 就不太准了. 今天用linux 下的setitimer()函数进行了定时 器的测 ...
- SpringMVC参数类型转化错误调试方法
- 关于List泛型的强制转换
当我们从数据库中查询出一些数据,有时返回的结果可能是List<Object>类型,而我们清楚的知道它的准确类型是List<User>,可能我们想直接的去进行类型的转换,你可能会 ...
- Codeforces Round #368 (Div. 2) D. Persistent Bookcase
Persistent Bookcase Problem Description: Recently in school Alina has learned what are the persisten ...
- mac eclipse 下安装subclipse
参考 http://www.cnblogs.com/yinxiangpei/articles/3859057.html 推荐安装homebrew 在安装javahl时注意版本对应 http://sub ...
- Gerrit清单库配置(转载)
From:http://fatalove.iteye.com/blog/1340334 gerrit清单库是用来配合repo使用的.清单库中列出了gerrit服务器上的其他版本库. 客户端通过repo ...