Wiktor Zawierucha
Wiktor Zawierucha

Reputation: 135

How to check if WMI Query returned 0 rows?

I'm working on a C# code that is obviously wrong. I'm trying to get a pendrive data with WMI query and after continuing with the operations, check if the query returned 0 rows to avoid bugs.

ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_USBDevice");
ManagementObjectCollection drive = searcher.Get();
if (drive == null)
{
    MessageBox.Show("Failed to read data.");
    Application.Exit();
}

Obviously the drive == null method does not work. How can I check it the proper way? And also, is this the proper way of getting a pendrive data?

Upvotes: 4

Views: 303

Answers (2)

Salah Akbari
Salah Akbari

Reputation: 39966

Use Count:

if (drive.Count == 0)
{
    MessageBox.Show("Failed to read data.");
    Application.Exit();
}

Upvotes: 2

Pankaj Kapare
Pankaj Kapare

Reputation: 7812

Make it foolproof:

if (drive==null || drive.Count == 0))
{
   MessageBox.Show("Failed to read data.");
   Application.Exit();
}

Upvotes: 5

Related Questions