我正在使用WMI进行查询以检查特定的驱动器号,如果它不存在,那么我想运行一个方法,使用特定的设置创建它。现在我遇到的问题是当我发送测试查询以查看驱动器号是否存在时,它返回空。没有错误或例外。
我该如何处理这种情况?
由于
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\cimv2",
@"SELECT * FROM Win32_Volume Where DriveLetter = '" + DriveLetter + "'");
foreach (ManagementObject queryObj in searcher.Get())
{
drives.CurrentDriveLetter = queryObj["DriveLetter"] == null ? "null" : queryObj["DriveLetter"].ToString();
drives.CurrentDriveSize = queryObj["Capacity"] == null ? "null" : queryObj["Capacity"].ToString();
drives.CurrentDriveName = queryObj["Label"] == null ? "null" : queryObj["Label"].ToString();
}
答案 0 :(得分:1)
根据您的评论,您只需确定ManagementObjectSearcher.Get
方法返回的集合是否包含元素。为此,您可以使用Count
属性。
试试此示例代码
using System;
using System.Collections.Generic;
using System.Management;
using System.Text;
namespace GetWMI_Info
{
class Program
{
static void Main(string[] args)
{
try
{
ManagementScope Scope;
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", "."), null);
Scope.Connect();
ObjectQuery Query = new ObjectQuery("SELECT * FROM Win32_Volume Where DriveLetter='X:' ");
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);
if (Searcher.Get().Count==0)
{
Console.WriteLine("Do something, when the collection is empty.");
}
else
foreach (ManagementObject WmiObject in Searcher.Get())
{
Console.WriteLine("{0} {1}","Name",WmiObject["Name"]);// String
}
}
catch (Exception e)
{
Console.WriteLine(String.Format("Exception {0} Trace {1}",e.Message,e.StackTrace));
}
Console.WriteLine("Press Enter to exit");
Console.Read();
}
}
}