为了更新我自己编写的 Windows 服务,我编写了一个 C# 程序来停止该服务,复制新的 DLL,然后重新启动它。
我的第一个方法如下:
ServiceController service = new ServiceController(serviceName);
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
// (...) copy the dll files
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
停止服务时,启动方法产生了以下错误:
Cannot start service FOVEA Service Debug on computer '.'.
at System.ServiceProcess.ServiceController.Start(String[] args) at
System.ServiceProcess.ServiceController.Start()
以管理员身份运行我的更新程序没有任何区别。
所以我尝试通过 net start/stop service
在命令行中启动/停止服务,效果很好,我将 C# 程序更改为以下内容:
Process p = Process.Start("net", "stop \"" + serviceName + "\"");
p.WaitForExit();
p = Process.Start("net", "start \"" + serviceName + "\"");
p.WaitForExit();
和以前一样,停止服务有效。 net start service
的调用无论如何输出
The service is not responding to the control function
more help is available by typing NET HELPMSG 2186
该服务是为本地登录用户(管理员)安装的,但我不明白为什么 net start
可以从命令行运行,但不能从代码中运行。我还尝试了以下方法:
- 为用户
NETWORK SERVICE
设置我的更新程序的完全权限 - 使用
p.StartInfo.Verb = "runas"
开始进程 - 将
p.StartInfo.WorkingDirectory
更改为Environment.SystemDirectory
- 将
p.MachineName
更改为Environment.MachineName
- 停止服务后让线程休眠5秒
但似乎没有任何影响。
有什么想法可以得到我想要的吗?预先感谢您的帮助。
最佳答案
试试这个方法:
ServiceController sc = new ServiceController(svr_name);
if (sc.Status != ServiceControllerStatus.Stopped)
{
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(30));
}
放置一些异常处理以避免错误。
关于c# - (重新)从我的 C# 代码中启动 Windows 服务不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23872513/