由于工作有这样的需求,于是各种寻找,但是都不满意,偶然间想起一个方法
1、修改服务的Program.cs文件如下
代码语言:javascript复制 static void Main(string[] args)
{
//LoadFile();
if (args == null || args.Length == 0)
{
ServiceBase[] servicesToRun;
servicesToRun = new ServiceBase[]
{
new ServiceClient()
};
ServiceBase.Run(servicesToRun);
}
else if (args.Length == 1 && System.Text.RegularExpressions.Regex.IsMatch(args[0], @"^[1-5]$"))
{
try
{
Process p = null;
ServiceController service = null;
switch (int.Parse(args[0]))
{
case 1:
//取当前可执行文件路径
var path = Process.GetCurrentProcess().MainModule.FileName "";
p = Process.Start("sc", "create AutoRunClient binpath= "" path "" displayName= AutoRunClient start= auto");
p.WaitForExit();
break;
case 2:
p = Process.Start("sc", "delete AutoRunClient");
p.WaitForExit();
break;
case 3:
service = new ServiceController("AutoRunClient");
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running);
break;
case 4:
service = new ServiceController("AutoRunClient");
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped);
break;
case 5:
service = new ServiceController("AutoRunClient");
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped);
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running);
break;
}
}
catch
{ }
}
}
这样,这个服务就做成了一个可当服务可当运行程序的一个功能
那么接下来,当我们需要重启自身的时候 可以这么干
Process.Start("ClientServer.exe","5");
这样就调用自身的有参的实例,然后就重启了