Ephraim
Ephraim

Reputation: 797

C# getdrives with type fixed but without usb harddisks?

I want to retrieve the list of fixed disks in a system. But C#s GetDrives Fixed Drives are including plug USB Harddisks.

Any idea how I may detect that a fixed Drive is not an USB harddisk or vica versa?

Upvotes: 6

Views: 6360

Answers (4)

Parsa
Parsa

Reputation: 1309

Here you can get list of USB hard disk.

//Add Reference System.Management and use namespace at the top of the code.
ManagementObjectSearcher searcher = new ManagementObjectSearcher("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"))
                { 
                    Console.WriteLine(String.Format("{0}" + "\\", c["Name"].ToString())); // here it will print USB drive letter
                }
            }

        }

Here you can get list of all fixed drives(System and USB hard disks):

        DriveInfo[] allDrives = DriveInfo.GetDrives(); 

        foreach (DriveInfo d in allDrives)
        {
            if (d.IsReady == true && d.DriveType == DriveType.Fixed)
            {
                Console.WriteLine("Drive {0}", d.Name);
                Console.WriteLine("  Drive type: {0}", d.DriveType);   
            }           
        }

If you compare them,then you can retrieve the list of fixed disks in a system but without USB hard disks.

Upvotes: 1

A.J.Bauer
A.J.Bauer

Reputation: 3001

Use this MSDN link for individual solutions (including finding drive letters): WMI Tasks: Disks and File Systems

Upvotes: 0

Wael Dalloul
Wael Dalloul

Reputation: 23004

use DriveType to detect the type of the drive:

using System.IO;

DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
  if (d.IsReady && d.DriveType == DriveType.Fixed)
  {
    // This is the drive you want...
  }
}

DriveInfo Class

EDIT1:

check the following link: How do I detected whether a hard drive is connected via USB?

Upvotes: 3

MSalters
MSalters

Reputation: 179819

Solution nicked from How to get serial number of USB-Stick in C# :

 //import the System.Management namespace at the top in your "using" statement.
 ManagementObjectSearch theSearcher = new ManagementObjectSearcher(
      "SELECT * FROM Win32_DiskDrive WHERE InterfaceType='USB'");

Upvotes: 4

Related Questions