Necesito realizar una comprobación en todas las unidades y ver si alguno de los VID/PID coincide con uno específico, si es así, necesito obtener la letra de la unidad de esa unidad flash. ¡Gracias a todos!¿Cómo puedo obtener VID/PID desde unidades flash USB en C#?
Respuesta
WMI debe ser capaz de manejar esto ...
Usted tendrá que añadir una referencia a la DLL System.Management y tendrá que tener el: "usando System.Management;" línea de ... Ver el enlace al final de imágenes, explicación más detallada ...
using System.Management;
// Get all the disk drives
ManagementObjectSearcher mosDisks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
// Loop through each object (disk) retrieved by WMI
foreach (ManagementObject moDisk in mosDisks.Get())
{
// Add the HDD to the list (use the Model field as the item's caption)
cmbHdd.Items.Add(moDisk["Model"].ToString());
}
private void cmbHdd_SelectedIndexChanged(object sender, EventArgs e)
{
// Get all the disk drives from WMI that match the Model name selected in the ComboBox
ManagementObjectSearcher mosDisks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE Model = '" + cmbHdd.SelectedItem + "'");
// Loop through the drives retrieved, although it should normally be only one loop going on here
foreach (ManagementObject moDisk in mosDisks.Get())
{
// Set all the fields to the appropriate values
lblType.Text = "Type: " + moDisk["MediaType"].ToString();
lblModel.Text = "Model: " + moDisk["Model"].ToString();
lblSerial.Text = "Serial: " + moDisk["SerialNumber"].ToString();
lblInterface.Text = "Interface: " + moDisk["InterfaceType"].ToString();
// The capacity in gigabytes is easily calculated
lblCapacity.Text = "Capacity: " + moDisk["Size"].ToString() + " bytes (" + Math.Round(((((double)Convert.ToDouble(moDisk["Size"])/1024)/1024)/1024), 2) + " GB)";
lblPartitions.Text = "Partitions: " + moDisk["Partitions"].ToString();
lblSignature.Text = "Signature: " + moDisk["Signature"].ToString();
lblFirmware.Text = "Firmware: " + moDisk["FirmwareRevision"].ToString();
lblCylinders.Text = "Cylinders: " + moDisk["TotalCylinders"].ToString();
lblSectors.Text = "Sectors: " + moDisk["TotalSectors"].ToString();
lblHeads.Text = "Heads: " + moDisk["TotalHeads"].ToString();
lblTracks.Text = "Tracks: " + moDisk["TotalTracks"].ToString();
lblBytesPerSect.Text = "Bytes per Sector: " + moDisk["BytesPerSector"].ToString();
lblSectorsPerTrack.Text = "Sectors per Track: " + moDisk["SectorsPerTrack"].ToString();
lblTracksPerCyl.Text = "Tracks per Cylinder: " + moDisk["TracksPerCylinder"].ToString();
}
}
De MSDN la clase Win32 para CIM_DiskDrive tiene los siguientes parámetros:
* Parece como si "DeviceID" es lo desea ...
class Win32_DiskDrive : CIM_DiskDrive
{
uint16 Availability;
uint32 BytesPerSector;
uint16 Capabilities[];
string CapabilityDescriptions[];
string Caption;
string CompressionMethod;
uint32 ConfigManagerErrorCode;
boolean ConfigManagerUserConfig;
string CreationClassName;
uint64 DefaultBlockSize;
string Description;
string DeviceID;
boolean ErrorCleared;
string ErrorDescription;
string ErrorMethodology;
string FirmwareRevision;
uint32 Index;
datetime InstallDate;
string InterfaceType;
uint32 LastErrorCode;
string Manufacturer;
uint64 MaxBlockSize;
uint64 MaxMediaSize;
boolean MediaLoaded;
string MediaType;
uint64 MinBlockSize;
string Model;
string Name;
boolean NeedsCleaning;
uint32 NumberOfMediaSupported;
uint32 Partitions;
string PNPDeviceID;
uint16 PowerManagementCapabilities[];
boolean PowerManagementSupported;
uint32 SCSIBus;
uint16 SCSILogicalUnit;
uint16 SCSIPort;
uint16 SCSITargetId;
uint32 SectorsPerTrack;
string SerialNumber;
uint32 Signature;
uint64 Size;
string Status;
uint16 StatusInfo;
string SystemCreationClassName;
string SystemName;
uint64 TotalCylinders;
uint32 TotalHeads;
uint64 TotalSectors;
uint64 TotalTracks;
uint32 TracksPerCylinder;
};
Top porción de código tomado de:
http://www.geekpedia.com/tutorial233_Getting-Disk-Drive-Information-using-WMI-and-Csharp.html
Si solo necesita verificar cuando el dispositivo está conectado, el problema es mucho más simple. Debe verificar el evento DBT_DEVICEARRIVAL
. Si está creando una aplicación de Windows Forms, puede hacerlo implementando la interfaz IMessageFilter
y pasándola a la función AddMessageFiler
en Application
. Si no está utilizando una aplicación de formularios, deberá derivar una clase de NativeWindow
y anular WndProc. Recuerde llamar al CreateHandle para que se agregue a la lista de mensajes de Windows.
Una vez que tenga la manera de recibir DBT_DEVICEARRIVAL
, tendrá que analizarlo. (La siguiente no fue escrito en un IDE por lo que no ha sido probado)
// Constants from from Dbt.h
const int WM_DEVICECHANGE = 0x219;
const int DBT_DEVICEARRIVAL = 0x8000;
const uint DBT_DEVTYP_DEVICEINTERFACE = 0x05;
const Guid GUID_DEVINTERFACE_USB_DEVICE = new Guid("A5DCBF10-6530-11D2-901F-00C04FB951ED");
bool PreFilterMessage(ref Message m)
{
if(m.Msg == case WM_DEVICECHANGE && m.WParam == DBT_DEVICEARRIVAL)
var broadcast = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(pnt, typeof(DEV_BROADCAST_HDR));
if(broadcast.dbch_DeviceType == DBT_DEVTYP_DEVICEINTERFACE)
{
var devInterface = (DEV_BROADCAST_DEVICEINTERFACE)Marshal.PtrToStructure(pnt, typeof(DEV_BROADCAST_DEVICEINTERFACE));
if(devInterface.dbcc_classguid = GUID_DEVINTERFACE_USB_DEVICE)
{
// devInterface.dbcc_name will contain the VID and PID for example:
// \\?\USB#Vid_067b&Pid_2517#6&12115ad4&2&1#{GUID}
DoSomthingSpecial(devInterface.dbcc_name);
}
}
}
return false;
}
[StructLayout(LayoutKind.Sequential)]
struct DEV_BROADCAST_HDR {
public uint dbch_Size;
public uint dbch_DeviceType;
public uint dbch_Reserved;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct DEV_BROADCAST_DEVICEINTERFACE
{
public int dbcc_size;
public int dbcc_devicetype;
public int dbcc_reserved;
public Guid dbcc_classguid;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=255)]
public string dbcc_name;
}
Si necesita para enumerar todos los dispositivos que ya están conectados me acaba de recomendar el uso de la WMI method. Si desea ver cómo hacerlo sin WMI, consulte el código USBView en el Windows Driver Development Kit, puede ayudarlo a comenzar.
public static bool GetDriveVidPid(string szDriveName, ref ushort wVID, ref ushort wPID)
{
bool bResult = false;
string szSerialNumberDevice = null;
ManagementObject oLogicalDisk = new ManagementObject("Win32_LogicalDisk.DeviceID='" + szDriveName.TrimEnd('\\') + "'");
foreach(ManagementObject oDiskPartition in oLogicalDisk.GetRelated("Win32_DiskPartition"))
{
foreach(ManagementObject oDiskDrive in oDiskPartition.GetRelated("Win32_DiskDrive"))
{
string szPNPDeviceID = oDiskDrive["PNPDeviceID"].ToString();
if(!szPNPDeviceID.StartsWith("USBSTOR"))
throw new Exception(szDriveName + " ist kein USB-Laufwerk.");
string[] aszToken = szPNPDeviceID.Split(new char[] { '\\', '&' });
szSerialNumberDevice = aszToken[aszToken.Length - 2];
}
}
if(null != szSerialNumberDevice)
{
ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(@"root\CIMV2", "Select * from Win32_USBHub");
foreach(ManagementObject oResult in oSearcher.Get())
{
object oValue = oResult["DeviceID"];
if(oValue == null)
continue;
string szDeviceID = oValue.ToString();
string[] aszToken = szDeviceID.Split(new char[] { '\\' });
if(szSerialNumberDevice != aszToken[aszToken.Length - 1])
continue;
int nTemp = szDeviceID.IndexOf(@"VID_");
if(0 > nTemp)
continue;
nTemp += 4;
wVID = ushort.Parse(szDeviceID.Substring(nTemp, 4), System.Globalization.NumberStyles.AllowHexSpecifier);
nTemp += 4;
nTemp = szDeviceID.IndexOf(@"PID_", nTemp);
if(0 > nTemp)
continue;
nTemp += 4;
wPID = ushort.Parse(szDeviceID.Substring(nTemp, 4), System.Globalization.NumberStyles.AllowHexSpecifier);
bResult = true;
break;
}
}
return bResult;
}
- 1. ¿Cómo puedo obtener todas las unidades USB (conectado)
- 2. Git bash no puede identificar unidades flash USB
- 3. Detectar unidad extraíble (por ejemplo, unidad flash USB) C/C++
- 4. Diferenciación programática entre unidad de disquete USB y unidad flash USB en Windows
- 5. Montar/Desmontar unidades USB con VBSCript
- 6. ¿Cómo puedo ciclar un dispositivo USB desde C#?
- 7. ¿Cómo puedo determinar si un dispositivo USB conectado es una unidad flash USB?
- 8. cómo determinar el fabricante de la unidad flash USB?
- 9. ¿Cómo puedo encontrar el tamaño de la unidad flash USB montada en C?
- 10. Listado de todas las unidades USB en Linux
- 11. Delphi - ¿Cómo obtener la lista de unidades de memoria extraíbles y memorias USB extraíbles?
- 12. Diferenciar entre unidad flash USB y disco duro USB en Windows
- 13. Android: Detecta una unidad flash USB conectada
- 14. ¿Lectura de datos desde USB usando C#?
- 15. ¿Cómo puedo fusionar/extender unidades de persistencia desde diferentes JAR?
- 16. ¿Cómo puedo obtener milisegundos desde la medianoche UTC en C?
- 17. Cómo descubrir dispositivos de almacenamiento USB y unidades de CD/DVD grabables (C#)
- 18. ¿Cómo volver a detectar una memoria flash USB por software?
- 19. Leyendo desde un dispositivo USB y enviándole consultas, en C#
- 20. Cómo obtener dispositivos USB Lista del navegador
- 21. Enumerar unidades externas
- 22. ¿Puedo raspar el flash?
- 23. ¿Cómo puedo comunicarme con un dispositivo USB HID en Delphi
- 24. ¿Puedo obtener una sesión de audio/aplicar unidades de audio para reproducir desde MPMusicPlayerController?
- 25. Escritura de aplicaciones portátiles de unidad USB en C#
- 26. ¿Cuál es su experiencia con las unidades flash?
- 27. Cómo obtener c buffer desde ImageMagick Image
- 28. ¿Cómo puedo formatear una fecha en Flash?
- 29. Conectar y desconectar dispositivos USB mediante programación
- 30. ¿Cómo puedo cambiar las unidades usando el sistema operativo python?
Esta es una solución mucho mejor para la pregunta de OP porque WMI es una exageración total. –