HOW CAN I SAFTLY REMOVE A USB DRIVE THROUGH C#?

Alex Leblois

Total Post:67

Points:471
Posted by  Alex Leblois
C# 
C#
 4873  View(s)
Ratings:
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);
        }
}
  1. Brad Pitt

    Post:61

    Points:429
    Re: How can I saftly remove a USB Drive through C#?

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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!