c# 即使服务又是可执行程序的代码实现

时间:2021-10-01 01:59:33

先看下代码

 namespace UpdaterServer
{
class Program
{
static void Main(string[] args)
{
if (args == null || args.Length == )
{
ServiceBase[] servicesToRun;
servicesToRun = new ServiceBase[]
{
new UpdateClientServer()
};
ServiceBase.Run(servicesToRun);
}
else if (args.Length == )
{
switch (args[])
{
//安装并启动服务
case "":
//取当前可执行文件路径
var path = Process.GetCurrentProcess().MainModule.FileName + "";
Process.Start("sc", "create UpdateClientServer binpath= \"" + path + "\" displayName= UpdateClientServer ");
Process.Start("sc", "start UpdateClientServer");
break;
case "":
Process.Start("sc", "stop UpdateClientServer");
Process.Start("sc", "delete UpdateClientServer");
break;
default:
Console.WriteLine("[1]安装并启动服务 [2]停止并卸载服务 [其他不识别字符]帮助信息 ");
break;
}
}
}
}
}