C#版Windows服務(wù)安裝卸載小工具
前言
在我們的工作中,經(jīng)常遇到Windows服務(wù)的安裝和卸載,在之前公司也普寫過(guò)一個(gè)WinForm程序選擇安裝路徑,這次再來(lái)個(gè)小巧靈活的控制臺(tái)程序,不用再選擇,只需放到需要安裝服務(wù)的目錄中運(yùn)行就可以實(shí)現(xiàn)安裝或卸載。
開發(fā)思路
1、由于系統(tǒng)的權(quán)限限制,在運(yùn)行程序時(shí)需要以管理員身份運(yùn)行
2、因?yàn)樾枰獙?shí)現(xiàn)安裝和卸載兩個(gè)功能,在程序運(yùn)行時(shí)提示本次操作是安裝還是卸載 需要輸入 1 或 2
3、接下來(lái)程序會(huì)查找當(dāng)前目錄中的可執(zhí)行文件并過(guò)濾程序本身和有時(shí)我們復(fù)制進(jìn)來(lái)的帶有vhost的文件,并列出列表讓操作者選擇(一般情況下只有一個(gè))
4、根據(jù)用戶所選進(jìn)行安裝或卸載操作
5、由于可能重復(fù)操作,需要遞歸調(diào)用一下
具體實(shí)現(xiàn)
首先們要操作服務(wù),需要用 System.ServiceProcess 來(lái)封裝實(shí)現(xiàn)類
using System;
using System.Collections;
using System.Configuration.Install;
using System.Linq;
using System.ServiceProcess;
namespace AutoInstallUtil
{
public class SystemServices
{
/// <summary>
/// 打開系統(tǒng)服務(wù)
/// </summary>
/// <param name="serviceName">系統(tǒng)服務(wù)名稱</param>
/// <returns></returns>
public static bool SystemServiceOpen(string serviceName)
{
try
{
using (var control = new ServiceController(serviceName))
{
if (control.Status != ServiceControllerStatus.Running)
{
control.Start();
}
}
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 關(guān)閉系統(tǒng)服務(wù)
/// </summary>
/// <param name="serviceName">系統(tǒng)服務(wù)名稱</param>
/// <returns></returns>
public static bool SystemServiceClose(string serviceName)
{
try
{
using (var control = new ServiceController(serviceName))
{
if (control.Status == ServiceControllerStatus.Running)
{
control.Stop();
}
}
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 重啟系統(tǒng)服務(wù)
/// </summary>
/// <param name="serviceName">系統(tǒng)服務(wù)名稱</param>
/// <returns></returns>
public static bool SystemServiceReStart(string serviceName)
{
try
{
using (var control = new ServiceController(serviceName))
{
if (control.Status == System.ServiceProcess.ServiceControllerStatus.Running)
{
control.Continue();
}
}
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 返回服務(wù)狀態(tài)
/// </summary>
/// <param name="serviceName">系統(tǒng)服務(wù)名稱</param>
/// <returns>1:服務(wù)未運(yùn)行 2:服務(wù)正在啟動(dòng) 3:服務(wù)正在停止 4:服務(wù)正在運(yùn)行 5:服務(wù)即將繼續(xù) 6:服務(wù)即將暫停 7:服務(wù)已暫停 0:未知狀態(tài)</returns>
public static int GetSystemServiceStatus(string serviceName)
{
try
{
using (var control = new ServiceController(serviceName))
{
return (int)control.Status;
}
}
catch
{
return 0;
}
}
/// <summary>
/// 返回服務(wù)狀態(tài)
/// </summary>
/// <param name="serviceName">系統(tǒng)服務(wù)名稱</param>
/// <returns>1:服務(wù)未運(yùn)行 2:服務(wù)正在啟動(dòng) 3:服務(wù)正在停止 4:服務(wù)正在運(yùn)行 5:服務(wù)即將繼續(xù) 6:服務(wù)即將暫停 7:服務(wù)已暫停 0:未知狀態(tài)</returns>
public static string GetSystemServiceStatusString(string serviceName)
{
try
{
using (var control = new ServiceController(serviceName))
{
var status = string.Empty;
switch ((int)control.Status)
{
case 1:
status = "服務(wù)未運(yùn)行";
break;
case 2:
status = "服務(wù)正在啟動(dòng)";
break;
case 3:
status = "服務(wù)正在停止";
break;
case 4:
status = "服務(wù)正在運(yùn)行";
break;
case 5:
status = "服務(wù)即將繼續(xù)";
break;
case 6:
status = "服務(wù)即將暫停";
break;
case 7:
status = "服務(wù)已暫停";
break;
case 0:
status = "未知狀態(tài)";
break;
}
return status;
}
}
catch
{
return "未知狀態(tài)";
}
}
/// <summary>
/// 安裝服務(wù)
/// </summary>
/// <param name="stateSaver"></param>
/// <param name="filepath"></param>
public static void InstallService(IDictionary stateSaver, string filepath)
{
try
{
var myAssemblyInstaller = new AssemblyInstaller
{
UseNewContext = true,
Path = filepath
};
myAssemblyInstaller.Install(stateSaver);
myAssemblyInstaller.Commit(stateSaver);
myAssemblyInstaller.Dispose();
}
catch (Exception ex)
{
throw new Exception("installServiceError/n" + ex.Message);
}
}
public static bool ServiceIsExisted(string serviceName)
{
ServiceController[] services = ServiceController.GetServices();
return services.Any(s => s.ServiceName == serviceName);
}
/// <summary>
/// 卸載服務(wù)
/// </summary>
/// <param name="filepath">路徑和文件名</param>
public static void UnInstallService(string filepath)
{
try
{
//UnInstall Service
var myAssemblyInstaller = new AssemblyInstaller
{
UseNewContext = true,
Path = filepath
};
myAssemblyInstaller.Uninstall(null);
myAssemblyInstaller.Dispose();
}
catch (Exception ex)
{
throw new Exception("unInstallServiceError/n" + ex.Message);
}
}
}
}
接下來(lái)我們封裝控制臺(tái)的操作方法為了實(shí)現(xiàn)循環(huán)監(jiān)聽(tīng)這里用了遞歸
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace AutoInstallUtil
{
class Program
{
static void Main(string[] args)
{
try
{
ServerAction();
}
catch (Exception ex)
{
Console.WriteLine("發(fā)生錯(cuò)誤:{0}", ex.Message);
}
Console.ReadKey();
}
/// <summary>
/// 操作
/// </summary>
private static void ServerAction()
{
Console.WriteLine("請(qǐng)輸入:1安裝 2卸載");
var condition = Console.ReadLine();
var currentPath = Environment.CurrentDirectory;
var currentFileNameVshost = Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName).ToLower();
var currentFileName = currentFileNameVshost.Replace(".vshost.exe", ".exe");
var files =
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("未找到可執(zhí)行文件,請(qǐng)確認(rèn)當(dāng)前目錄有需要安裝的服務(wù)程序");
}
else
{
Console.WriteLine("找到目錄有如下可執(zhí)行文件,請(qǐng)選擇需要安裝或卸載的文件序號(hào):");
}
int i = 0;
foreach (var file in files)
{
Console.WriteLine("序號(hào):{0} 文件名:{1}", i, file);
i++;
}
var serviceFileIndex = Console.ReadLine();
var servicePathName = currentPath + "\\" + files[Convert.ToInt32(serviceFileIndex)];
if (condition == "1")
{
SystemServices.InstallService(null, servicePathName);
}
else
{
SystemServices.UnInstallService(servicePathName);
}
Console.WriteLine("**********本次操作完畢**********");
ServerAction();
}
}
}
到此為止簡(jiǎn)單的安裝程序就寫完了,為了醒目我選了個(gè)紅色的西紅柿來(lái)做為圖標(biāo),這樣顯示些
源碼和程序:安裝卸載Windows服務(wù)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- C#創(chuàng)建Windows服務(wù)的實(shí)現(xiàn)方法
- C#對(duì)Windows服務(wù)組的啟動(dòng)與停止操作
- C#編寫Windows服務(wù)程序詳細(xì)步驟詳解(圖文)
- 使用C#創(chuàng)建Windows服務(wù)的實(shí)例代碼
- C#通過(guò)創(chuàng)建Windows服務(wù)啟動(dòng)程序的方法詳解
- C#實(shí)現(xiàn)操作windows系統(tǒng)服務(wù)(service)的方法
- 基于C#實(shí)現(xiàn)Windows服務(wù)狀態(tài)啟動(dòng)和停止服務(wù)的方法
- c#創(chuàng)建windows服務(wù)入門教程實(shí)例
- c#創(chuàng)建windows服務(wù)(Windows Services)詳細(xì)步驟
- C#編寫Windows服務(wù)實(shí)例代碼
- C#啟動(dòng)windows服務(wù)方法的相關(guān)問(wèn)題分析
- C#創(chuàng)建控制Windows服務(wù)
相關(guān)文章
C# WPF如何反射加載Geometry幾何圖形數(shù)據(jù)圖標(biāo)
這篇文章主要介紹了C# WPF如何反射加載Geometry幾何圖形數(shù)據(jù)圖標(biāo),幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-03-03
解析C#中用Process類終止進(jìn)程,執(zhí)行命令的深入分析
本篇文章是對(duì)C#中用Process類終止進(jìn)程,執(zhí)行命令進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
C#實(shí)現(xiàn)的陰歷陽(yáng)歷互相轉(zhuǎn)化類實(shí)例
這篇文章主要介紹了C#實(shí)現(xiàn)的陰歷陽(yáng)歷互相轉(zhuǎn)化類,結(jié)合實(shí)例形式分析了C#針對(duì)日期的轉(zhuǎn)換與計(jì)算相關(guān)操作技巧,需要的朋友可以參考下2017-06-06
C#實(shí)現(xiàn)獲得某個(gè)枚舉的所有名稱
這篇文章主要為大家詳細(xì)介紹了C#如何實(shí)現(xiàn)獲得某個(gè)枚舉的所有名稱,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,有需要的小伙伴可以參考一下2025-01-01

