Users Pricing

forum

Home Forums How can I saftly remove a USB Drive through C#? – MindStick

How can I saftly remove a USB Drive through C#?

Anonymous User 7125 16 Oct 2013

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 Answers

Markdown for AI

A clean, structured version of this page for AI assistants and LLMs.

Open .md