【问题标题】:C# Error while trying to start or stop a service尝试启动或停止服务时出现 C# 错误
【发布时间】:2015-03-26 15:32:19
【问题描述】:

目前正在尝试编写一个可以检测服务特定状态的 C# 程序。如果服务正在运行,程序将关闭它。如果服务停止,程序将运行它。

下面是我的代码:

        ServiceController sc = new ServiceController("RtkAudioService");

        Console.WriteLine("Status = " + sc.Status);
        Console.WriteLine("Can Pause and Continue = " + sc.CanPauseAndContinue);
        Console.WriteLine("Can ShutDown = " + sc.CanShutdown);
        Console.WriteLine("Can Stop = " + sc.CanStop);
        Console.WriteLine("Machine Name = " + sc.MachineName);

        if (sc.Status.Equals(ServiceControllerStatus.Stopped))
        {
            sc.Start();
        } 
        else if (sc.Status.Equals(ServiceControllerStatus.Running))
        {
            sc.Stop();
        }

我尝试为我的电脑停止/运行各种服务,但失败了。 RtkAudioService 只是我失败的例子之一。所有的错误信息都是一样的:

An unhandled exception of type 'System.InvalidOperationException' occurred in System.ServiceProcess.dll

Additional information: Cannot open RtkAudioService service on computer '.'.

你们知道发生了什么吗?

【问题讨论】:

  • 不确定,因为我没有该服务,但 ServiceController 构造函数需要 DisplayName 而不是 ServiceName。可能你应该通过Realtek Audio Service
  • @Steve 根据 msdn 可以是。我尝试了这个并选择了一个随机服务来在我的机器上启动/停止。我可以使用名称启动它,但需要以管理员身份运行才能停止它。 InvalidOperationException 的内部异常是Access is denied
  • 是的,使用 ServiceName 检查并且它可以工作。所以只剩下权限选项
  • this question中的同样问题
  • 那么,是不是我们必须添加应用程序清单文件并将requestedExecutionLevel级别更改为“requireAdministrator”?

标签: c# .net service


【解决方案1】:

我遇到了同样的问题,我解决了在启动或停止服务后添加此代码:

sc.WaitForStatus(ServiceControllerStatus."status");

【讨论】:

    【解决方案2】:

    以管理员身份运行VS,它解决了调试问题。

    因为程序必须有权运行或停止服务可能是管理员权限。

    【讨论】:

      【解决方案3】:

      同样的情况刚刚发生在我身上,并通过在检查状态之前添加“sc.Refresh()”来解决(可能状态不是最新的,因此您正在尝试启动正在运行的进程)。 我会尝试在 if 之前打印服务的状态,并确保结果符合您的期望。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多