tags:

views:

705

answers:

3

I wrote the following code to get the physical media serial number but in one of my computers it returns null instead. Does anybody know what the problem is? Thanks.

var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
foreach( ManagementObject mo in searcher.Get() )
{
    Console.WriteLine("Serial: {0}", mo["SerialNumber"]);
}
+2  A: 

The Serial Number is optional, defined by the manufacturer, and for your device it is either blank or unsupported by the driver.

Virtually all hard drives have a serial number, but most USB-style Flash memory sticks do not (generally a cost issue). I would imagine most unbranded CD/DVD/BD discs would also be non-serialized.

devstuff
The system I use has both XP and Win7 RC1 and only has one HDD installed, in Win7 it returns the HDD serial number but in XP it returns null.
Mohammadreza
You mean that the for the same disk the serial number is returned in Windows 7 and not returned in Windows XP? In any case, use wbemtest.exe to verify that your code returns correct values - if the SerialNumber property is <null> in Windows XP there is not much you can do about it.
Uros Calakovic
A: 

You may want to look at this msdn forum thread: WMI Win32_PhysicalMedia ID in Vista and 7

It seems that from Vista and onward 'Win32_PhysicalMedia' has been replaced by 'Win32_DiskDrive'.

que que
A: 

Here is the code I used, the serial number somehow is returned raw with each pair of chars reversed (strange) and using Win32_PhysicalMedia gave different results if I ran the code as a user or an Administrator(more strange) - Windows 7 Ultimate, VS 2008 using VB only:

Function GetHDSerial() As String Dim strHDSerial As String = String.Empty Dim index As Integer = 0 Dim Data As String Dim Data2 As String Dim ndx As Integer

Dim query As New SelectQuery("Win32_DiskDrive")
Dim search As New ManagementObjectSearcher(query)
Dim info As ManagementObject
Try
    For Each info In search.Get()
        Data = info("SerialNumber")
        Data2 = ""
        For ndx = 1 To Data.Length - 1 Step 2
            Data2 = Data2 & Chr(Val("&H" & Mid(Data, ndx, 2)))
        Next ndx
        Data = String.Empty
        For ndx = 1 To Data2.Length - 1 Step 2
            Data = Data & Mid(Data2, ndx + 1, 1) & Mid(Data2, ndx, 1)
        Next
        Data2 = Data
        If Len(Data) < 8 Then Data2 = "00000000" 'some drives have no s/n
        Data2 = Replace(Data2, " ", "") ' some drives pad spaces in the s/n
        'forget removeable drives
        If InStr(info("MediaType").ToString, "Fixed", CompareMethod.Text) > 0 Then
           strHDSerial = strHDSerial & "Drive " & index.ToString & " SN: " & Data2 & vbCrLf
           index += 1
        End If
    Next
Catch ex As Exception
    strHDSerial = "Error retrieving SN for Drive " 
    msgbox(index.ToString)
End Try
Return strHDSerial

End Function

dev-null