Get Drive Name of Connected USB using C#
Get drive letters of connected USB storage devices. These can then be used in file I/O operations.
using System.Management;
Code:
private static List<string> GetConnectedUsbDrives() { List<string> usbDriveLetters = new List<string>( ); var usbDrives = new ManagementObjectSearcher( "SELECT DeviceID FROM Win32_DiskDrive WHERE InterfaceType='USB'" ); foreach ( ManagementObject drive in usbDrives.Get( ) ) { var partitions = new ManagementObjectSearcher( "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + drive[ "DeviceID" ].ToString( ) + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition" ); foreach ( var partition in partitions.Get( ) ) { var logicalDrives = new ManagementObjectSearcher( "ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + partition[ "DeviceID" ].ToString( ) + "'} WHERE AssocClass = Win32_LogicalDiskToPartition" ); foreach ( var logicalDrive in logicalDrives.Get( ) ) { usbDriveLetters.Add( logicalDrive[ "Caption" ].ToString( ) ); } } } return usbDriveLetters; }
Implementation:
static void Main ( string[ ] args ) { foreach ( var s in GetConnectedUsbDrives() ) { Debug.WriteLine( "Drive : " + s ); } Console.ReadLine( ); }
No comments:
Post a Comment
Thank You for Your Comments. We will get back to you soon.