---
title: "How can I saftly remove a USB Drive through C#?"  
description: "How can I saftly remove a USB Drive through C#?"  
author: "Anonymous User"  
published: 2013-10-16  
updated: 2013-10-16  
canonical: https://www.mindstick.com/forum/1695/how-can-i-saftly-remove-a-usb-drive-through-c-sharp  
category: "c#"  
tags: ["c#"]  
reading_time: 2 minutes  

---

# How can I saftly remove a USB Drive through C#?

I want to [remove](https://yourviews.mindstick.com/story/4554/8-harmful-weeds-to-remove-from-garden) a [USB](https://www.mindstick.com/articles/13074/what-makes-usb-c-cables-better-than-other-usb-cables) drive with the help of C# and When I am using below [function](https://www.mindstick.com/articles/13001/multi-statement-table-valued-user-defined-function-in-sql-server), it is able to get drive letter but, when I remove the USB stick and [test](https://yourviews.mindstick.com/story/1427/explosive-facts-about-trinity-test-world-s-first-nuclear-bomb) 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);
        }
}
```

## Replies

### Reply by Anonymous User

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();
```


---

Original Source: https://www.mindstick.com/forum/1695/how-can-i-saftly-remove-a-usb-drive-through-c-sharp

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
