我试着用WMI来破坏我的C:驱动器。
我正在运行Windows7Pro x64。
Console.WriteLine(SMARTManager.Instance.SMARTHDD.Defrag("C:", ref ERR));函数:
public string Defrag(string a_DriveName, ref string ERR)
{
try
{
ManagementObject classInstance =
new ManagementObject("root\\CIMV2",
String.Format("Win32_Volume.DeviceID='{0}'", a_DriveName),
null);
// Obtain in-parameters for the method
ManagementBaseObject inParams =
classInstance.GetMethodParameters("Defrag");
// Add the input parameters.
inParams["Force"] = true;
// Execute the method and obtain the return values.
ManagementBaseObject outParams =
classInstance.InvokeMethod("Defrag", inParams, null);
// List outParams
string callback = "Out parameters:\n" + "ReturnValue: " + outParams["ReturnValue"];
return callback;
}
catch (ManagementException err)
{
ERR = "An error occurred while trying to execute the WMI method: " + err.Message;
}
return null;
}我从WMI代码创建者那里得到了这段代码,但是当我运行它时,它会返回一个令人兴奋的消息,上面写着“没有找到”。
还有人试过这个吗?
发布于 2012-08-08 21:59:00
导致此错误的原因是将错误的对象路径传递给ManagementObject构造函数,DeviceID看起来类似于\\?\Volume{3a7a882b-8713-11e0-bfc8-806e6f6e6963}\,因此要解决问题,必须传递有效的DeviceID或修改代码以使用Win32_Volume类的Name属性。
检查下面的示例代码,它使用Name属性
using System;
using System.Collections.Generic;
using System.Management;
using System.Text;
namespace GetWMI_Info
{
class Program
{
public static void Defrag(string a_DriveName)
{
try
{
string ComputerName = "localhost";
ManagementScope Scope;
if (!ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase))
{
ConnectionOptions Conn = new ConnectionOptions();
Conn.Username = "";
Conn.Password = "";
Conn.Authority = "ntlmdomain:DOMAIN";
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), Conn);
}
else
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);
Scope.Connect();
string WQL = String.Format("SELECT * FROM Win32_Volume Where Name='{0}'", a_DriveName);
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"]);
}
}
catch (Exception e)
{
Console.WriteLine(String.Format("Exception {0} Trace {1}",e.Message,e.StackTrace));
}
}
static void Main(string[] args)
{
//the drive name must be escaped
Defrag("F:\\\\");
Console.WriteLine("Press Enter to exit");
Console.Read();
}
}https://stackoverflow.com/questions/11869896
复制相似问题