C#版Windows服务安装卸载小工具
前言
在我们的工作中,经常遇到Windows服务的安装和卸载,在之前公司也普写过一个WinForm程序选择安装路径,这次再来个小巧灵活的控制台程序,不用再选择,只需放到需要安装服务的目录中运行就可以实现安装或卸载。
开发思路
1、由于系统的权限限制,在运行程序时需要以管理员身份运行
2、因为需要实现安装和卸载两个功能,在程序运行时提示本次操作是安装还是卸载 需要输入1或2
3、接下来程序会查找当前目录中的可执行文件并过滤程序本身和有时我们复制进来的带有vhost的文件,并列出列表让操作者选择(一般情况下只有一个)
4、根据用户所选进行安装或卸载操作
5、由于可能重复操作,需要递归调用一下
具体实现
首先们要操作服务,需要用 System.ServiceProcess来封装实现类
usingSystem;
usingSystem.Collections;
usingSystem.Configuration.Install;
usingSystem.Linq;
usingSystem.ServiceProcess;
namespaceAutoInstallUtil
{
publicclassSystemServices
{
///<summary>
///打开系统服务
///</summary>
///<paramname="serviceName">系统服务名称</param>
///<returns></returns>
publicstaticboolSystemServiceOpen(stringserviceName)
{
try
{
using(varcontrol=newServiceController(serviceName))
{
if(control.Status!=ServiceControllerStatus.Running)
{
control.Start();
}
}
returntrue;
}
catch
{
returnfalse;
}
}
///<summary>
///关闭系统服务
///</summary>
///<paramname="serviceName">系统服务名称</param>
///<returns></returns>
publicstaticboolSystemServiceClose(stringserviceName)
{
try
{
using(varcontrol=newServiceController(serviceName))
{
if(control.Status==ServiceControllerStatus.Running)
{
control.Stop();
}
}
returntrue;
}
catch
{
returnfalse;
}
}
///<summary>
///重启系统服务
///</summary>
///<paramname="serviceName">系统服务名称</param>
///<returns></returns>
publicstaticboolSystemServiceReStart(stringserviceName)
{
try
{
using(varcontrol=newServiceController(serviceName))
{
if(control.Status==System.ServiceProcess.ServiceControllerStatus.Running)
{
control.Continue();
}
}
returntrue;
}
catch
{
returnfalse;
}
}
///<summary>
///返回服务状态
///</summary>
///<paramname="serviceName">系统服务名称</param>
///<returns>1:服务未运行2:服务正在启动3:服务正在停止4:服务正在运行5:服务即将继续6:服务即将暂停7:服务已暂停0:未知状态</returns>
publicstaticintGetSystemServiceStatus(stringserviceName)
{
try
{
using(varcontrol=newServiceController(serviceName))
{
return(int)control.Status;
}
}
catch
{
return0;
}
}
///<summary>
///返回服务状态
///</summary>
///<paramname="serviceName">系统服务名称</param>
///<returns>1:服务未运行2:服务正在启动3:服务正在停止4:服务正在运行5:服务即将继续6:服务即将暂停7:服务已暂停0:未知状态</returns>
publicstaticstringGetSystemServiceStatusString(stringserviceName)
{
try
{
using(varcontrol=newServiceController(serviceName))
{
varstatus=string.Empty;
switch((int)control.Status)
{
case1:
status="服务未运行";
break;
case2:
status="服务正在启动";
break;
case3:
status="服务正在停止";
break;
case4:
status="服务正在运行";
break;
case5:
status="服务即将继续";
break;
case6:
status="服务即将暂停";
break;
case7:
status="服务已暂停";
break;
case0:
status="未知状态";
break;
}
returnstatus;
}
}
catch
{
return"未知状态";
}
}
///<summary>
///安装服务
///</summary>
///<paramname="stateSaver"></param>
///<paramname="filepath"></param>
publicstaticvoidInstallService(IDictionarystateSaver,stringfilepath)
{
try
{
varmyAssemblyInstaller=newAssemblyInstaller
{
UseNewContext=true,
Path=filepath
};
myAssemblyInstaller.Install(stateSaver);
myAssemblyInstaller.Commit(stateSaver);
myAssemblyInstaller.Dispose();
}
catch(Exceptionex)
{
thrownewException("installServiceError/n"+ex.Message);
}
}
publicstaticboolServiceIsExisted(stringserviceName)
{
ServiceController[]services=ServiceController.GetServices();
returnservices.Any(s=>s.ServiceName==serviceName);
}
///<summary>
///卸载服务
///</summary>
///<paramname="filepath">路径和文件名</param>
publicstaticvoidUnInstallService(stringfilepath)
{
try
{
//UnInstallService
varmyAssemblyInstaller=newAssemblyInstaller
{
UseNewContext=true,
Path=filepath
};
myAssemblyInstaller.Uninstall(null);
myAssemblyInstaller.Dispose();
}
catch(Exceptionex)
{
thrownewException("unInstallServiceError/n"+ex.Message);
}
}
}
}
接下来我们封装控制台的操作方法为了实现循环监听这里用了递归
usingSystem;
usingSystem.Diagnostics;
usingSystem.IO;
usingSystem.Linq;
namespaceAutoInstallUtil
{
classProgram
{
staticvoidMain(string[]args)
{
try
{
ServerAction();
}
catch(Exceptionex)
{
Console.WriteLine("发生错误:{0}",ex.Message);
}
Console.ReadKey();
}
///<summary>
///操作
///</summary>
privatestaticvoidServerAction()
{
Console.WriteLine("请输入:1安装2卸载");
varcondition=Console.ReadLine();
varcurrentPath=Environment.CurrentDirectory;
varcurrentFileNameVshost=Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName).ToLower();
varcurrentFileName=currentFileNameVshost.Replace(".vshost.exe",".exe");
varfiles=
Directory.GetFiles(currentPath)
.Select(o=>Path.GetFileName(o).ToLower())
.ToList()
.Where(
o=>
o!=currentFileNameVshost
&&o!=currentFileName
&&o.ToLower().EndsWith(".exe")
&&o!="installutil.exe"
&&!o.ToLower().EndsWith(".vshost.exe"))
.ToList();
if(files.Count==0)
{
Console.WriteLine("未找到可执行文件,请确认当前目录有需要安装的服务程序");
}
else
{
Console.WriteLine("找到目录有如下可执行文件,请选择需要安装或卸载的文件序号:");
}
inti=0;
foreach(varfileinfiles)
{
Console.WriteLine("序号:{0}文件名:{1}",i,file);
i++;
}
varserviceFileIndex=Console.ReadLine();
varservicePathName=currentPath+"\\"+files[Convert.ToInt32(serviceFileIndex)];
if(condition=="1")
{
SystemServices.InstallService(null,servicePathName);
}
else
{
SystemServices.UnInstallService(servicePathName);
}
Console.WriteLine("**********本次操作完毕**********");
ServerAction();
}
}
}
到此为止简单的安装程序就写完了,为了醒目我选了个红色的西红柿来做为图标,这样显示些
源码和程序:安装卸载Windows服务
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。