2

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


                }
4

1 回答 1

2

根据您的评论,您只需要确定该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();
        }
    }
}
于 2013-04-06T00:16:06.303 回答