Reputation: 135
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
Reputation: 39966
Use Count
:
if (drive.Count == 0)
{
MessageBox.Show("Failed to read data.");
Application.Exit();
}
Upvotes: 2
Reputation: 7812
Make it foolproof:
if (drive==null || drive.Count == 0))
{
MessageBox.Show("Failed to read data.");
Application.Exit();
}
Upvotes: 5