gpt4 book ai didi

c# - WMI 查询不返回任何内容

转载 作者:太空宇宙 更新时间:2023-11-03 11:05:52 25 4
gpt4 key购买 nike

我正在使用 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();


}

最佳答案

根据您的评论,您只需要确定 ManagementObjectSearcher.Get 返回的集合是否方法有元素。为此,您可以使用 Count属性(property)。

试试这个示例代码

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();
}
}
}

关于c# - WMI 查询不返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15843948/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com