Tags: | Categories: Code Snippets Posted by Vitaly Zayko on 12/16/2008 12:32 PM | Comments (0)

First of all add reference to System.Management sysm assembly.
Then run something like this:

1:/// <summary>
2:/// Retuns list of all Removable drives aailable
3:/// </summary>
4:/// <param name="UsbDrives">Structure to store drive names (e.g. "D:", "E:" etc.</param>
5:/// <returns>true if at least one removable is available</returns>
6:public bool GetRemovableDisks(out IList<string> UsbDrives)
7:{
8:   // Add System.Management reference. Then
9:    bool result = false;
10:   UsbDrives = new List<string>();
11:   using (System.Management.ManagementClass managementClass = new System.Management.ManagementClass("Win32_Diskdrive"))
12:   {
13:       using (System.Management.ManagementObjectCollection driveCollection = managementClass.GetInstances())
14:       {
15:           foreach(System.Management.ManagementObject driveObject in driveCollection)
16:               foreach (System.Management.ManagementObject drivePartition in driveObject.GetRelated("Win32_DiskPartition"))
17:                   foreach (System.Management.ManagementBaseObject logicalDisk in drivePartition.GetRelated("Win32_LogicalDisk"))
18:                   {
19:                       string drive = (logicalDisk["Name"]).ToString();
20:                       string driveDescription = logicalDisk.Properties["Description"].Value.ToString();
21:                       if (driveDescription.Equals("Removable Disk", StringComparison.InvariantCultureIgnoreCase))
22:                       {
23:                           UsbDrives.Add(drive);
24:                           result = true;
25:                       }
26:                   } 
27:       }
28:   }
29:   return result;
30:}
31:

Comments are closed