c# - (重新)从我的 C# 代码中启动 Windows 服务不起作用

标签 c# windows service

为了更新我自己编写的 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/

相关文章:

c# - 使用 Azure AD 时将用户重定向到自定义登录页面

android - 如何避免在具有不同功能的数据库中同时使用同一张表

android mainactivity和服务流程

c# - JSON 阅读器期待一个值但发现 'function'

c# - clr.sll!StrongNameSignatureVerification CPU 消耗

c# - 为 RequiredAttribute 提供自定义消息

c# Windows form应用程序窗体问题

windows - xcopy/排除问题

c++ - 在运行时跟踪非托管函数调用?

android - 检查网络连接android