mrtaikandi
mrtaikandi

Reputation: 6958

Problem with Win32_PhysicalMedia SerialNumber property

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

Upvotes: 2

Views: 10479

Answers (2)

dev-null
dev-null

Reputation: 31

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

Upvotes: 3

devstuff
devstuff

Reputation: 8387

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.

Upvotes: 3

Related Questions