nGX
nGX

Reputation: 1068

WMI query returns nothing

I am making a query with WMI to check for a particular drive letter, if it does not exist then I want to run a method that will create it with specific settings. Now the problem I am facing is when I send a test query to see if the drive letter exists, it returns empty. No error or exception.

How would I handle this type of situation?

Thanks

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


                }

Upvotes: 2

Views: 3328

Answers (1)

RRUZ
RRUZ

Reputation: 136391

Following your comments you only need determine if the collection returned by the ManagementObjectSearcher.Get method has elements. For that you can use the Count property.

Try this sample code

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

Upvotes: 2

Related Questions