2010-11-03 45 views
22

Deseo obtener el número de serie del disco duro. ¿Cómo puedo hacer eso? he intentado con dos código, pero no estoy recibiendoObtener número de serie del disco duro

StringCollection propNames = new StringCollection(); 
ManagementClass driveClass = new ManagementClass("Win32_DiskDrive"); 
PropertyDataCollection props = driveClass.Properties; 
foreach (PropertyData driveProperty in props) 
{ 
    propNames.Add(driveProperty.Name); 
} 
int idx = 0; 
ManagementObjectCollection drives = driveClass.GetInstances(); 
foreach (ManagementObject drv in drives) 
     { 
      Label2.Text+=(idx + 1); 
      foreach (string strProp in propNames) 
      { 
      //Label2.Text+=drv[strProp]; 
     Response.Write(strProp + " = " + drv[strProp] + "</br>"); 
      } 
    } 

En éste no estoy recibiendo ningún número de serie único.
y segundo uno es

string drive = "C"; 
ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"" + drive + ":\""); 
disk.Get(); 
Label3.Text = "VolumeSerialNumber="+ disk["VolumeSerialNumber"].ToString(); 

Aquí estoy recibiendo VolumeSerialNumber. Pero no es único. Si formateo el disco duro, esto cambiará. ¿Cómo puedo conseguir esto?

Respuesta

30

Hm, mirando su primer conjunto de código, creo que ha recuperado (¿tal vez?) El modelo de disco duro. El número de serie viene de Win32_PhysicalMedia.

Obtener duro modelo Drive

ManagementObjectSearcher searcher = new 
    ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive"); 

    foreach(ManagementObject wmi_HD in searcher.Get()) 
    { 
    HardDrive hd = new HardDrive(); 
    hd.Model = wmi_HD["Model"].ToString(); 
    hd.Type = wmi_HD["InterfaceType"].ToString(); 
    hdCollection.Add(hd); 
    } 

obtener el número de serie

searcher = new 
    ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia"); 

    int i = 0; 
    foreach(ManagementObject wmi_HD in searcher.Get()) 
    { 
    // get the hard drive from collection 
    // using index 
    HardDrive hd = (HardDrive)hdCollection[i]; 

    // get the hardware serial no. 
    if (wmi_HD["SerialNumber"] == null) 
    hd.SerialNo = "None"; 
    else 
    hd.SerialNo = wmi_HD["SerialNumber"].ToString(); 

    ++i; 
    } 

Source

Espero que esto ayude :)

+1

¿Quería publicar la misma fuente dos veces? – dotalchemy

+0

Vaya, lo edité y lo arreglé. – Sprunth

+1

Gracias por su respuesta .... aquí estoy obteniendo "Ninguna" cada vez ... – Joby

11

He utilizado el siguiente método en un proyecto y está funcionando con éxito.

private string identifier(string wmiClass, string wmiProperty) 
//Return a hardware identifier 
{ 
    string result = ""; 
    System.Management.ManagementClass mc = new System.Management.ManagementClass(wmiClass); 
    System.Management.ManagementObjectCollection moc = mc.GetInstances(); 
    foreach (System.Management.ManagementObject mo in moc) 
    { 
     //Only get the first one 
     if (result == "") 
     { 
      try 
      { 
       result = mo[wmiProperty].ToString(); 
       break; 
      } 
      catch 
      { 
      } 
     } 
    } 
    return result; 
} 

puede llamar al método anterior como se menciona a continuación,

string modelNo = identifier("Win32_DiskDrive", "Model"); 
string manufatureID = identifier("Win32_DiskDrive", "Manufacturer"); 
string signature = identifier("Win32_DiskDrive", "Signature"); 
string totalHeads = identifier("Win32_DiskDrive", "TotalHeads"); 

Si necesita un identificador único, utilizar una combinación de estos identificadores.

+0

gracias por responder ..... después de formatear el HD si este mismo valor se repetirá? – Joby

-1

La mejor manera que he encontrado es, descargue un archivo DLL de here

A continuación, agregue el DLL a su proyecto.

A continuación, añadir código:

[DllImportAttribute("HardwareIDExtractorC.dll")] 
public static extern String GetIDESerialNumber(byte DriveNumber); 

A continuación, llamar a la identificación del disco duro desde donde se lo necesita

GetIDESerialNumber(0).Replace(" ", string.Empty); 

Nota: ir a las características de la DLL en el explorador y ajuste "Construir la acción "a" Recurso incrustado "

+0

¿Todavía tienes el dll? – DreTaX

3

Utilice el comando" vol "shell y analice el serial desde su salida, así. Works al menos en Win7

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace CheckHD 
{ 
     class HDSerial 
     { 
      const string MY_SERIAL = "F845-BB23"; 
      public static bool CheckSerial() 
      { 
       string res = ExecuteCommandSync("vol"); 
       const string search = "Number is"; 
       int startI = res.IndexOf(search, StringComparison.InvariantCultureIgnoreCase); 

       if (startI > 0) 
       { 
        string currentDiskID = res.Substring(startI + search.Length).Trim(); 
        if (currentDiskID.Equals(MY_SERIAL)) 
         return true; 
       } 
       return false; 
      } 

      public static string ExecuteCommandSync(object command) 
      { 
       try 
       { 
        // create the ProcessStartInfo using "cmd" as the program to be run, 
        // and "/c " as the parameters. 
        // Incidentally, /c tells cmd that we want it to execute the command that follows, 
        // and then exit. 
        System.Diagnostics.ProcessStartInfo procStartInfo = 
         new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command); 

        // The following commands are needed to redirect the standard output. 
        // This means that it will be redirected to the Process.StandardOutput StreamReader. 
        procStartInfo.RedirectStandardOutput = true; 
        procStartInfo.UseShellExecute = false; 
        // Do not create the black window. 
        procStartInfo.CreateNoWindow = true; 
        // Now we create a process, assign its ProcessStartInfo and start it 
        System.Diagnostics.Process proc = new System.Diagnostics.Process(); 
        proc.StartInfo = procStartInfo; 
        proc.Start(); 
        // Get the output into a string 
        string result = proc.StandardOutput.ReadToEnd(); 
        // Display the command output. 
        return result; 
       } 
       catch (Exception) 
       { 
        // Log the exception 
        return null; 
       } 
      } 
     } 
    } 
+0

Ah, sí, eso funcionará espléndidamente en cada versión de idioma de Windows. No es que la salida de texto de ese comando sea diferente en una versión rusa, japonesa o noruega de Windows en comparación con una versión en inglés, ¿o sí? –

+0

Esto da el número de serie de la unidad lógica, no el disco duro – Aferrercrafter

7

Hay una manera simple para que la respuesta de @ Sprunth.

private void GetAllDiskDrives() 
    { 
     var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive"); 

     foreach (ManagementObject wmi_HD in searcher.Get()) 
     { 
      HardDrive hd = new HardDrive(); 
      hd.Model = wmi_HD["Model"].ToString(); 
      hd.InterfaceType = wmi_HD["InterfaceType"].ToString(); 
      hd.Caption = wmi_HD["Caption"].ToString(); 

      hd.SerialNo =wmi_HD.GetPropertyValue("SerialNumber").ToString();//get the serailNumber of diskdrive 

      hdCollection.Add(hd); 
     } 

} 


public class HardDrive 
{ 
    public string Model { get; set; } 
    public string InterfaceType { get; set; } 
    public string Caption { get; set; } 
    public string SerialNo { get; set; } 
} 
+0

'El nombre 'hdCollection' no existe en el contexto actual' ... – Woland

0

A continuación un método totalmente funcional para obtener disco duro número de serie:

public string GetHardDiskSerialNo() 
    { 
     ManagementClass mangnmt = new ManagementClass("Win32_LogicalDisk"); 
     ManagementObjectCollection mcol = mangnmt.GetInstances(); 
     string result = ""; 
     foreach (ManagementObject strt in mcol) 
     { 
      result += Convert.ToString(strt["VolumeSerialNumber"]); 
     } 
     return result; 
    } 
+0

LogicalDisk serie no es lo mismo que HardDisk Serial, puede intentar y ver que difieren – Aferrercrafter

0

estoy usando esto:

<!-- language: c# --> 
private static string wmiProperty(string wmiClass, string wmiProperty){ 
    using (var searcher = new ManagementObjectSearcher($"SELECT * FROM {wmiClass}")) { 
    try { 
        IEnumerable<ManagementObject> objects = searcher.Get().Cast<ManagementObject>(); 
        return objects.Select(x => x.GetPropertyValue(wmiProperty)).FirstOrDefault().ToString().Trim(); 
       } catch (NullReferenceException) { 
        return null; 
       } 
      } 
     } 
0

Aquí hay un código que puede ayudar:

ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive"); 

string serial_number=""; 

foreach (ManagementObject wmi_HD in searcher.Get()) 
{ 
    serial_number = wmi_HD["SerialNumber"].ToString(); 
} 

MessageBox.Show(serial_number); 
+1

Bienvenido a SO. Como obviamente se ha invertido mucho esfuerzo en esta respuesta, podría ser difícil entender si solo se trata de un código. Es habitual comentar la solución con algunas oraciones. Por favor edite su respuesta y agregue alguna explicación. Además, recuerde formatear el código antes de publicar la respuesta. – MikaS

Cuestiones relacionadas