How to get the drive letter of USB device using WMI

前端 未结 2 1811
野性不改
野性不改 2021-02-04 21:17

I need to track the USB insertion and removal events from the C# application so I came up with the following ideas based on the other questions on SO.

I can\'t use this

2条回答
  •  误落风尘
    2021-02-04 21:51

    This is a refactored version of michalk's answer for C# 8.

    I used it in combination with the answers for this, Detecting USB drive insertion and removal using windows service and c#, related question

            static IEnumerable<(string deviceId, string pnpDeviceId, string driveLetter)> SelectDeviceInformation()
            {
                foreach (ManagementObject device in SelectDevices())
                {
                    var deviceId = (string)device.GetPropertyValue("DeviceID");
                    var pnpDeviceId = (string)device.GetPropertyValue("PNPDeviceID");
                    var driveLetter = (string)SelectPartitions(device).SelectMany(SelectDisks).Select(disk => disk["Name"]).Single();
    
                    yield return (deviceId, pnpDeviceId, driveLetter);
                }
    
                static IEnumerable SelectDevices() => new ManagementObjectSearcher(
                        @"SELECT * FROM Win32_DiskDrive WHERE InterfaceType LIKE 'USB%'").Get()
                    .Cast();
    
                static IEnumerable SelectPartitions(ManagementObject device) => new ManagementObjectSearcher(
                        "ASSOCIATORS OF {Win32_DiskDrive.DeviceID=" +
                        "'" + device.Properties["DeviceID"].Value + "'} " +
                        "WHERE AssocClass = Win32_DiskDriveToDiskPartition").Get()
                    .Cast();
    
                static IEnumerable SelectDisks(ManagementObject partition) => new ManagementObjectSearcher(
                        "ASSOCIATORS OF {Win32_DiskPartition.DeviceID=" +
                        "'" + partition["DeviceID"] + "'" +
                        "} WHERE AssocClass = Win32_LogicalDiskToPartition").Get()
                    .Cast();
            }
    

提交回复
热议问题