Home > DeveloperSection > Forums > How can I saftly remove a USB Drive through C#?
Alex Leblois
Alex Leblois

Total Post:67

Points:471
Posted on    October-16-2013 7:22 AM

 C# C# 
Ratings:


 1 Reply(s)
 3349  View(s)
Rate this:

I want to remove a USB drive with the help of C# and When I am using below function, it is able to get drive letter but, when I remove the USB stick and test this function, it doesn’t go to the Exception.

Please someone help me!

    public void GetDriveLetter()
    {
        try
        {
            ManagementObjectSearcher c = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_DiskDrive where InterfaceType='USB'");
            foreach (ManagementObject queryObj in managementObjectSearcher.Get())
            {
                foreach (ManagementObject managementObject in queryObj.GetRelated("Win32_DiskPartition"))
                {
                    foreach (ManagementBaseObject managementBaseObject in managementObject.GetRelated("Win32_LogicalDisk"))
                    {
                        usbDriveLetter = String.Format("{0}" + "\\", managementBaseObject["Name"].ToString());
                    }
                }
            }
        }
        catch (ManagementException e)
        {
            MessageBox.Show(e.StackTrace);
        }
}


Brad Pitt
Brad Pitt

Total Post:61

Points:429
Posted on    October-16-2013 7:53 AM

Try below code: -

ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_DiskDrive where InterfaceType='USB'");
return (from ManagementObject queryObj in managementObjectSearcher.Get()
from ManagementObject managementObject in queryObj.GetRelated("Win32_DiskPartition")
select managementObject).Select(managementObject => managementObject.GetRelated("Win32_LogicalDisk").Count > 0).FirstOrDefault();

Don't want to miss updates? Please click the below button!

Follow MindStick