类型或命名空间名称“ServiceController”无法找到

12

我正在尝试在C#中检查一个服务,我已经添加了System.ServiceProcess.dll

但我收到了以下错误:

Error 2 The type or namespace name 'ServiceController' could not be found (are you missing a using directive or an assembly reference?) D:\App\Form1.cs 247 13 App

我的代码如下:

private void button13_Click(object sender, EventArgs e)
{
    ServiceController sc = new ServiceController("Spooler");

    if (sc.Status == ServiceControllerStatus.Running)
    {
        MessageBox.Show("The service is running.");
    }
}

我是不是需要一个 "using" 语句?

4个回答

16

您需要添加对 System.ServiceProcess.dll 的引用。

输入图像描述

之后,您就可以在 Visual Studio 中看到它作为一个可添加到项目中的 using 语句之一:

输入图像描述


5
专业提示:当您尝试使用.NET Framework中的类时,如果出现以下消息:

The type or namespace name '...' could not be found (are you missing a using directive or an assembly reference?)

请在MSDN Library中查找该类型,并在继承层次结构部分下找到所需的命名空间和程序集。 继承层次结构
System.Object   
  System.MarshalByRefObject  
    System.ComponentModel.Component  
      System.ServiceProcess.ServiceController  

命名空间:System.ServiceProcess
程序集: System.ServiceProcess (在System.ServiceProcess.dll中)

然后确保您已经引用了该程序集并且有一个使用指令来引用该命名空间(假设您不想完全限定名称)。


谢谢,这对未来会很有用。 - Mike

3

是的,位于顶部。

使用 System.ServiceProcess;


1
对于我来说(Visual Studio 2012),当在“using”中输入时,它不是默认添加的。我必须添加引用并搜索 System.ServiceProcess 组件。 (我相信在旧版本的 Studio 中,它位于 .NET 选项卡中)。希望这能帮助未来的观众!

这个答案与被接受的答案完全相同,只是没有支持图形。 - newfurniturey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接