When I use this function in c#, it is able to get drive letter but, when I remove the USB stick and test this function, it doesnt go to the Exception.
So could someone help me with where I am going wrong in the function code?
public void GetDriveLetter()
{
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_DiskDrive where InterfaceType='USB'");
foreach (ManagementObject queryObj in searcher.Get())
{
foreach (ManagementObject b in queryObj.GetRelated("Win32_DiskPartition"))
{
foreach (ManagementBaseObject c in b.GetRelated("Win32_LogicalDisk"))
{
// writer.WriteLine("{0}" + "\\", c["Name"].ToString()); // here it will print drive letter
usbDriveLetter = String.Format("{0}" + "\\", c["Name"].ToString());
}
}
}
}
catch (ManagementException e)
{
MessageBox.Show(e.StackTrace);
}
//CombinedPath = System.IO.Path.Combine(usbDriveLetter.Trim(), path2.Trim());
}
You Method wont throw an
Exceptionas nothing is breaking. If you want to throw andExceptionwhen no usb’s are found then you can do this.Update: will return true if any USB device is found