为什么“禁用”或“重新启动”方法不起作用(在C#中使用WMI)

时间:2017-07-18 17:07:55

标签: c# wmi system.management

我刚写了3个不同的代码。其中一个工作正常。但是其他两个,不工作并抛出ManagementException消息:

  

此方法未在任何类

中实现

以下是可以正常使用的代码:

string ComputerName = "localhost";
ManagementScope Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);

Scope.Connect();

string WQL = String.Format("SELECT * FROM Win32_Volume");
ObjectQuery Query = new ObjectQuery(WQL);
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);

foreach (ManagementObject ClassInstance in Searcher.Get())
{
    ManagementBaseObject inParams = ClassInstance.GetMethodParameters("Defrag");
    ManagementBaseObject outParams = ClassInstance.InvokeMethod("Defrag", inParams, null);
    Console.WriteLine("{0,-35} {1,-40}", "DefragAnalysis", outParams["DefragAnalysis"]);
    Console.WriteLine("{0,-35} {1,-40}", "ReturnValue", outParams["ReturnValue"]);
}

Console.ReadLine();

这是不起作用的代码并抛出异常(参见基本相同的代码)改变的一件事是使用的WMI类。 InvokeMethod上发生异常。

string ComputerName = "localhost";
ManagementScope Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);
Scope.Connect();
string WQL = String.Format("SELECT * FROM Win32_PnPEntity");
ObjectQuery Query = new ObjectQuery(WQL);
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);

foreach (ManagementObject ClassInstance in Searcher.Get())
{                
    ManagementBaseObject inParams = ClassInstance.GetMethodParameters("Disable");
    ManagementBaseObject outParams = ClassInstance.InvokeMethod("Disable", inParams, null);
    Console.WriteLine("{0,-35} {1,-40}", "ReturnValue", outParams["ReturnValue"]);
    Console.WriteLine("{0,-35} {1,-40}", "rebootNeeded", outParams["rebootNeeded"]);
}

Console.ReadLine();

我还尝试使用“重置”方法而不是“禁用”。这是行不通的。但这一次,GetMethodParameters发生了异常。它说这种方法没有在任何类中实现。

string ComputerName = "localhost";
ManagementScope Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);
Scope.Connect();
string WQL = String.Format("SELECT * FROM Win32_PnPEntity");
ObjectQuery Query = new ObjectQuery(WQL);
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);

foreach (ManagementObject ClassInstance in Searcher.Get())
{                
    ManagementBaseObject inParams = ClassInstance.GetMethodParameters("Reset");
    ManagementBaseObject outParams = ClassInstance.InvokeMethod("Reset", inParams, null);
    Console.WriteLine("{0,-35} {1,-40}", "ReturnValue", outParams["ReturnValue"]);
    Console.WriteLine("{0,-35} {1,-40}", "rebootNeeded", outParams["rebootNeeded"]);
}

Console.ReadLine();

我需要一个启用和禁用PNP设备的代码,同样,我需要使用WMI类来保持与其余代码相同的标准,因此我需要使用命名空间System.Management;

1 个答案:

答案 0 :(得分:0)

用于禁用设备的代码是正确的,但是您需要以管理员权限运行它。未经管理员许可,我正在获得System.Management.ManagementException'通用故障'。