krikk
krikk

Reputation: 25

USB Drive Removal Code in C#

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

Upvotes: 1

Views: 1023

Answers (2)

Jethro
Jethro

Reputation: 5916

You Method wont throw an Exception as nothing is breaking. If you want to throw and Exception when no usb's are found then you can do this.

if (searcher.Get().Count == 0)
    throw new ApplicationException("No Usb drives connected");

Update: will return true if any USB device is found

ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_DiskDrive where InterfaceType='USB'");

        return (from ManagementObject queryObj in searcher.Get()
                from ManagementObject b in queryObj.GetRelated("Win32_DiskPartition")
                select b).Select(b => b.GetRelated("Win32_LogicalDisk").Count > 0).FirstOrDefault();

Upvotes: 1

Davide Piras
Davide Piras

Reputation: 44595

Probably it does not go to the exception because as you have removed the USB stick, the device is not even listed and no exception happens.

Why do you want to generate an exception at all in case the usb stick is not plugged in?

also, you could eventually have better luck replacing the specific exception in the catch definition with a simple Exception object but I don't think this is the issue, as I said above probably no exception is thrown simply because you don^t list anymore the removed device.

Upvotes: 0

Related Questions