c# - Obtenga el número de serie del dispositivo de almacenamiento usb en.net core 2.1
.net-core usb-drive (2)
Esta clase realiza una serie de consultas sobre la clase WMI
Win32_DiskDrive
y sus asociados:
Win32_DiskDriveToDiskPartition
y
CIM_LogicalDiskBasedOnPartition
, para recuperar información sobre las unidades USB activas en un sistema (local o remoto).
Puede parecer redundante (probablemente porque lo es), ya que acaba de solicitar el número de serie de unidades USB.
Pero, nunca se sabe lo que necesitará a continuación, y podría ser útil para otra persona.
Requiere
Microsoft .Net System.Management 4.5
para .Net Core 2.1 (paquete NuGet)
Se puede encontrar e instalar fácilmente con Visual Studio
NuGet Package Manager
.
Sobre el soporte de
Linux
, lea aquí:
Instrumental de administración de Windows ahora un bus formal con Linux 4.13
Además, esté atento al
paquete de compatibilidad de Windows para .NET Core
.
Nuevos conjuntos multiplataforma se agregan y actualizan constantemente.
La clase principal implementa todas las funcionalidades requeridas y tiene una estructura bastante simple.
Las consultas WMI utilizan la sintaxis de Associator, un método para correlacionar objetos de clase WMI relacionados entre sí.
El significado de las propiedades de clase se explica por sí mismo.
Se puede instanciar de esta manera:
SystemUSBDrives systemUSBDrives = new SystemUSBDrives("[Computer Name]");
Cuando
[Computer Name]
es nulo o está vacío, utiliza el nombre de la máquina local.
Para obtener la Lista de dispositivos USB y sus propiedades, llame al método
GetUSBDrivesInfo()
:
var USBDrivesEnum = systemUSBDrives.GetUSBDrivesInfo([UserName], [Password], [Domain]);
[UserName], [Password], [Domain]
se utilizan para conectarse a un Dominio NT.
Estos parámetros, si no son necesarios, pueden ser nulos o una cadena vacía.
Ejemplo de instancia de clase y llamada de función
(
Local Machine, no authentication
):
SystemUSBDrives systemUSBDrives = new SystemUSBDrives(null);
var USBDrivesEnum = systemUSBDrives.GetUSBDrivesInfo(null, null, null);
Probado en:
Visual Studio Pro 15.7.6 - 15.8.5
.Net Framework Core 2.1
C# 6.0 -> 7.3
.Net System.Management 4.5
using System.Management;
public class SystemUSBDrives
{
string m_ComputerName = string.Empty;
public SystemUSBDrives(string ComputerName)
{
this.m_ComputerName = string.IsNullOrEmpty(ComputerName)
? Environment.MachineName
: ComputerName;
}
public class USBDriveInfo
{
public bool Bootable { get; private set; }
public bool BootPartition { get; private set; }
public string Caption { get; private set; }
public string DeviceID { get; private set; }
public UInt32 DiskIndex { get; private set; }
public string FileSystem { get; private set; }
public string FirmwareRevision { get; private set; }
public UInt64 FreeSpace { get; private set; }
public string InterfaceType { get; private set; }
public string LogicalDisk { get; private set; }
public bool MediaLoaded { get; private set; }
public string MediaType { get; private set; }
public string Model { get; private set; }
public UInt32 Partitions { get; private set; }
public UInt64 PartitionBlockSize { get; private set; }
public UInt64 PartitionNumberOfBlocks { get; private set; }
public UInt64 PartitionStartingOffset { get; private set; }
public string PNPDeviceID { get; private set; }
public bool PrimaryPartition { get; private set; }
public string SerialNumber { get; private set; }
public UInt64 Size { get; private set; }
public string Status { get; private set; }
public bool SupportsDiskQuotas { get; private set; }
public UInt64 TotalCylinders { get; private set; }
public UInt32 TotalHeads { get; private set; }
public UInt64 TotalSectors { get; private set; }
public UInt64 TotalTracks { get; private set; }
public UInt32 TracksPerCylinder { get; private set; }
public string VolumeName { get; private set; }
public string VolumeSerialNumber { get; private set; }
public void GetDiskDriveInfo(ManagementObject DiskDrive)
{
this.Caption = DiskDrive["Caption"]?.ToString();
this.DeviceID = DiskDrive["DeviceID"]?.ToString();
this.FirmwareRevision = DiskDrive["FirmwareRevision"]?.ToString();
this.InterfaceType = DiskDrive["InterfaceType"]?.ToString();
this.MediaLoaded = (bool?)DiskDrive["MediaLoaded"] ?? false;
this.MediaType = DiskDrive["MediaType"]?.ToString();
this.Model = DiskDrive["Model"]?.ToString();
this.Partitions = (UInt32?)DiskDrive["Partitions"] ?? 0;
this.PNPDeviceID = DiskDrive["PNPDeviceID"]?.ToString();
this.SerialNumber = DiskDrive["SerialNumber"]?.ToString();
this.Size = (UInt64?)DiskDrive["Size"] ?? 0L;
this.Status = DiskDrive["Status"]?.ToString();
this.TotalCylinders = (UInt64?)DiskDrive["TotalCylinders"] ?? 0;
this.TotalHeads = (UInt32?)DiskDrive["TotalHeads"] ?? 0U;
this.TotalSectors = (UInt64?)DiskDrive["TotalSectors"] ?? 0;
this.TotalTracks = (UInt64?)DiskDrive["TotalTracks"] ?? 0;
this.TracksPerCylinder = (UInt32?)DiskDrive["TracksPerCylinder"] ?? 0;
}
public void GetDiskPartitionInfo(ManagementObject Partitions)
{
this.Bootable = (bool?)Partitions["Bootable"] ?? false;
this.BootPartition = (bool?)Partitions["BootPartition"] ?? false;
this.DiskIndex = (UInt32?)Partitions["DiskIndex"] ?? 0;
this.PartitionBlockSize = (UInt64?)Partitions["BlockSize"] ?? 0;
this.PartitionNumberOfBlocks = (UInt64?)Partitions["NumberOfBlocks"] ?? 0;
this.PrimaryPartition = (bool?)Partitions["PrimaryPartition"] ?? false;
this.PartitionStartingOffset = (UInt64?)Partitions["StartingOffset"] ?? 0;
}
public void GetLogicalDiskInfo(ManagementObject LogicalDisk)
{
this.FileSystem = LogicalDisk["FileSystem"]?.ToString();
this.FreeSpace = (UInt64?)LogicalDisk["FreeSpace"] ?? 0;
this.LogicalDisk = LogicalDisk["DeviceID"]?.ToString();
this.SupportsDiskQuotas = (bool?)LogicalDisk["SupportsDiskQuotas"] ?? false;
this.VolumeName = LogicalDisk["VolumeName"]?.ToString();
this.VolumeSerialNumber = LogicalDisk["VolumeSerialNumber"]?.ToString();
}
}
public List<USBDriveInfo> GetUSBDrivesInfo(string UserName, string Password, string Domain)
{
List<USBDriveInfo> WMIQueryResult = new List<USBDriveInfo>();
ConnectionOptions ConnOptions = GetConnectionOptions(UserName, Password, Domain);
EnumerationOptions mOptions = GetEnumerationOptions(false);
ManagementScope mScope = new ManagementScope(@"//" + this.m_ComputerName + @"/root/CIMV2", ConnOptions);
SelectQuery selQuery = new SelectQuery("SELECT * FROM Win32_DiskDrive " +
"WHERE InterfaceType=''USB''");
mScope.Connect();
using (ManagementObjectSearcher moSearcher = new ManagementObjectSearcher(mScope, selQuery, mOptions))
{
foreach (ManagementObject moDiskDrive in moSearcher.Get())
{
USBDriveInfo usbInfo = new USBDriveInfo();
usbInfo.GetDiskDriveInfo(moDiskDrive);
var relQuery = new RelatedObjectQuery("Associators of {Win32_DiskDrive.DeviceID=''" +
moDiskDrive.Properties["DeviceID"].Value.ToString() + "''} " +
"where AssocClass=Win32_DiskDriveToDiskPartition");
using (ManagementObjectSearcher moAssocPart = new ManagementObjectSearcher(mScope, relQuery, mOptions))
{
foreach (ManagementObject moAssocPartition in moAssocPart.Get())
{
usbInfo.GetDiskPartitionInfo(moAssocPartition);
relQuery = new RelatedObjectQuery("Associators of {Win32_DiskPartition.DeviceID=''" +
moAssocPartition.Properties["DeviceID"].Value.ToString() + "''} " +
"where AssocClass=CIM_LogicalDiskBasedOnPartition");
using (ManagementObjectSearcher moLogDisk = new ManagementObjectSearcher(mScope, relQuery, mOptions))
{
foreach (ManagementObject moLogDiskEnu in moLogDisk.Get())
{
usbInfo.GetLogicalDiskInfo(moLogDiskEnu);
moLogDiskEnu.Dispose();
}
}
moAssocPartition.Dispose();
}
WMIQueryResult.Add(usbInfo);
}
moDiskDrive.Dispose();
}
return WMIQueryResult;
}
} //GetUSBDrivesInfo()
private ConnectionOptions GetConnectionOptions(string UserName, string Password, string DomainAuthority)
{
ConnectionOptions ConnOptions = new ConnectionOptions()
{
EnablePrivileges = true,
Timeout = ManagementOptions.InfiniteTimeout,
Authentication = AuthenticationLevel.PacketPrivacy,
Impersonation = ImpersonationLevel.Impersonate,
Username = UserName,
Password = Password,
Authority = DomainAuthority //Authority = "NTLMDOMAIN:[domain]"
};
return ConnOptions;
}
private System.Management.EnumerationOptions GetEnumerationOptions(bool DeepScan)
{
System.Management.EnumerationOptions mOptions = new System.Management.EnumerationOptions()
{
Rewindable = false, //Forward only query => no caching
ReturnImmediately = true, //Pseudo-async result
DirectRead = true, //True => Direct access to the WMI provider, no super class or derived classes
EnumerateDeep = DeepScan //False => only immediate derived class members are returned.
};
return mOptions;
}
} //SystemUSBDrives
¿Cómo puedo obtener el número de serie del dispositivo de almacenamiento USB en .net core 2.1 ?
Encontré diferentes soluciones, pero lamentablemente no funcionan debido a la falta de registro de Windows y wmi en .net core.
En Powershell es realmente simple, pero no pude encontrar una implementación en Powershell Core .
PS C:/> Get-Disk | Select-Object SerialNumber
SerialNumber
------------
0008_0D02_0021_9852.
Prefiero una solución sin instalaciones adicionales en los clientes (Win, Linux, Mac).
No estoy seguro de si esto es exactamente lo que está buscando, pero aquí hay un código que he usado en el pasado.
using System.Management;
public class USBDeviceInfo
{
public string Availability { get; set; }
public string Caption { get; set; }
public string ClassCode { get; set; }
public uint ConfigManagerErrorCode { get; set; }
public bool ConfigManagerUserConfig { get; set; }
public string CreationClassName { get; set; }
public string CurrentAlternateSettings { get; set; }
public string CurrentConfigValue { get; set; }
public string Description { get; set; }
public string DeviceID { get; set; }
public string ErrorCleared { get; set; }
public string ErrorDescription { get; set; }
public string GangSwitched { get; set; }
public string InstallDate { get; set; }
public string LastErrorCode { get; set; }
public string Name { get; set; }
public string NumberOfConfigs { get; set; }
public string NumberOfPorts { get; set; }
public string PNPDeviceID { get; set; }
public string PowerManagementCapabilities { get; set; }
public string PowerManagementSupported { get; set; }
public string ProtocolCode { get; set; }
public string Status { get; set; }
public string StatusInfo { get; set; }
public string SubclassCode { get; set; }
public string SystemCreationClassName { get; set; }
public string SystemName { get; set; }
public string USBVersion { get; set; }
}
public static List<USBDeviceInfo> GetUSBDevices()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"Select * From Win32_USBHub");
ManagementObjectCollection collection = searcher.Get();
List<USBDeviceInfo> devices = new List<USBDeviceInfo>();
foreach (var device in collection)
{
USBDeviceInfo deviceInfo = new USBDeviceInfo();
deviceInfo.Availability = (string)device.GetPropertyValue("Availability");
deviceInfo.Caption = (string)device.GetPropertyValue("Caption");
deviceInfo.ClassCode = (string)device.GetPropertyValue("ClassCode");
deviceInfo.ConfigManagerErrorCode = (uint)device.GetPropertyValue("ConfigManagerErrorCode");
deviceInfo.ConfigManagerUserConfig = (bool)device.GetPropertyValue("ConfigManagerUserConfig");
deviceInfo.CreationClassName = (string)device.GetPropertyValue("CreationClassName");
deviceInfo.CurrentAlternateSettings = (string)device.GetPropertyValue("CurrentAlternateSettings");
deviceInfo.CurrentConfigValue = (string)device.GetPropertyValue("CurrentConfigValue");
deviceInfo.Description = (string)device.GetPropertyValue("Description");
deviceInfo.DeviceID = (string)device.GetPropertyValue("DeviceID");
deviceInfo.ErrorCleared = (string)device.GetPropertyValue("ErrorCleared");
deviceInfo.ErrorDescription = (string)device.GetPropertyValue("ErrorDescription");
deviceInfo.GangSwitched = (string)device.GetPropertyValue("GangSwitched");
deviceInfo.InstallDate = (string)device.GetPropertyValue("InstallDate");
deviceInfo.LastErrorCode = (string)device.GetPropertyValue("LastErrorCode");
deviceInfo.Name = (string)device.GetPropertyValue("Name");
deviceInfo.NumberOfConfigs = (string)device.GetPropertyValue("NumberOfConfigs");
deviceInfo.NumberOfPorts = (string)device.GetPropertyValue("NumberOfPorts");
deviceInfo.PNPDeviceID = (string)device.GetPropertyValue("PNPDeviceID");
deviceInfo.PowerManagementCapabilities = (string)device.GetPropertyValue("PowerManagementCapabilities");
deviceInfo.PowerManagementSupported = (string)device.GetPropertyValue("PowerManagementSupported");
deviceInfo.ProtocolCode = (string)device.GetPropertyValue("ProtocolCode");
deviceInfo.Status = (string)device.GetPropertyValue("Status");
deviceInfo.StatusInfo = (string)device.GetPropertyValue("StatusInfo");
deviceInfo.SubclassCode = (string)device.GetPropertyValue("SubclassCode");
deviceInfo.SystemCreationClassName = (string)device.GetPropertyValue("SystemCreationClassName");
deviceInfo.SystemName = (string)device.GetPropertyValue("SystemName");
deviceInfo.USBVersion = (string)device.GetPropertyValue("USBVersion");
devices.Add(deviceInfo);
}
collection.Dispose();
searcher.Dispose();
return devices;
}