2010-11-03 26 views
22

Desidero ottenere il numero di serie del disco rigido. Come posso farlo? ho provato con due code, ma non ricevoOttieni numero di serie disco rigido

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>"); 
      } 
    } 

In questo io non sto ottenendo alcun numero di serie unico.
E secondo è

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

Qui sto ottenendo VolumeSerialNumber. Ma non è unico. Se formatto il disco rigido, questo cambierà. Come posso ottenere questo?

risposta

30

Hm, guardando il tuo primo set di codice, penso che tu abbia recuperato (forse?) Il modello del disco rigido. Il numero di serie viene da Win32_PhysicalMedia.

ottenere duro modello rigido

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); 
    } 

Prendi il numero di 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

Spero che questo aiuti :)

+1

Volevi postare due volte la stessa fonte? – dotalchemy

+0

Oops, l'ho modificato e risolto. – Sprunth

+1

Grazie per la risposta .... eccomi ricevendo "Nessuno" Ogni volta ... – Joby

11

ho usato il seguente metodo in un progetto e sta funzionando con successo.

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; 
} 

è possibile chiamare il metodo di cui sopra, come indicato di seguito,

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

Se avete bisogno di un identificatore univoco, utilizzare una combinazione di questi ID.

+0

grazie per la risposta ..... dopo aver formattato l'HD se questo stesso valore si ripeterà? – Joby

-1

Il modo migliore che ho trovato è, scaricare una DLL da here

Quindi, aggiungere la dll al progetto.

Quindi, aggiungere il codice:

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

Poi, chiamare l'ID del disco rigido da dove serve

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

Nota: andare alle proprietà della DLL in Esplora risorse e impostare "Build azione "a" Risorse incorporate "

+0

Hai ancora la DLL? – DreTaX

3

Utilizzare il comando di shell" vol "e analizzare il seriale dall'output, come questo. lavora almeno in 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ì, funzionerà magnificamente su tutte le versioni linguistiche di Windows. Non è come l'output testuale di quel comando è diverso in una versione russa, giapponese o norvegese di Windows rispetto a una versione inglese, vero? –

+0

Fornisce la seriale dell'unità logica, non il disco rigido – Aferrercrafter

7

C'è un modo semplice per @ risposta di 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

'Il nome 'hdCollection' non esiste nel contesto corrente' ... – Woland

0

Qui di seguito un metodo completamente funzionale per ottenere il numero di serie del disco rigido:

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

Il numero di LogicalDisk non è lo stesso di quello del disco rigido di serie, è possibile provare e vedere che differiscono – Aferrercrafter

0

Sto usando questo:

<!-- 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

Ecco po 'di codice che può aiutare:

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

Benvenuti in SO. Ovviamente, in questa risposta, è ovvio che potrebbe essere difficile capire se è solo un codice. È normale commentare la soluzione con poche frasi. Si prega di modificare la risposta e aggiungere qualche spiegazione. Inoltre, ricorda di formattare il codice prima di pubblicare la risposta. – MikaS

Problemi correlati