How to Find USB device serial Number in VB.NET

Posted on 2009-07-15
Medium Priority
Last Modified: 2013-11-07
I have found a VB code to find the serial number of an USB device at http://omnibus.uni-freiburg.de/~albers/snippets/usbinfo10.zip. I have not tried it in VB as I want to use the code in VB.NET. However converting it in VB.NET, I had to change many of things in it. Some how I managed to resolve all the complier errors. But executing the application gives runtime error. "arithmetic operation result in an overflow" at the place shown in the following extract of code. Possibly it may be overflow caused by constant value of "&HC30C" assigned to a SHORT datatype.
So, whether the "&HC30C" value is correct ?
whether VB.NET compitible code of USBINFO10 is available ?
Can experts help me to convert USBINFO10 code in to VB.NET ?
Private Structure typGUID ' 10h/16 bytes, no paddings
        Public lData1 As Integer ' +00-03:  DWORD
        Public iData2 As Short  ' +04-05:  WORD
        Public iData3 As Short ' +06-07:  WORD
        <VBFixedString(8), System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst:=8)> Public abData4() As Byte		
    End Structure
GUID_CLASS_USBHUB = DEFINE_GUID(&HF18A0E88, &HC30C, &H11D0, &H88, &H15, &H0, &HA0, &HC9, &H6, &HBE, &HD8)
Private Function DEFINE_GUID(ByVal lData1 As Integer, ByVal iData2 As Integer, ByVal iData3 As Short, ByVal bData4_1 As Byte, ByVal bData4_2 As Byte, ByVal bData4_3 As Byte, ByVal bData4_4 As Byte, ByVal bData4_5 As Byte, ByVal bData4_6 As Byte, ByVal bData4_7 As Byte, ByVal bData4_8 As Byte) As typGUID
        Dim GUIDTMP As typGUID
        'following 1 line added to resolve null pointer error 
        GUIDTMP.abData4 = New Byte() {0, 0, 0, 0, 0, 0, 0, 0}
        With GUIDTMP
            .lData1 = lData1
            .iData2 = iData2    ' <-----  geting overflow error here
            .iData3 = iData3
            .abData4(0) = bData4_1
            .abData4(1) = bData4_2
            .abData4(2) = bData4_3
            .abData4(3) = bData4_4
            .abData4(4) = bData4_5
            .abData4(5) = bData4_6
            .abData4(6) = bData4_7
            .abData4(7) = bData4_8
        End With
               DEFINE_GUID = GUIDTMP
    End Function

Open in new window

Question by:kkp01
  • 2

Expert Comment

ID: 24864850
Try the code below from

    Private Function GetVolumeSerial(ByVal DriveLetter As String) As String
        'Check for valid drive letter argument. 
        Dim ValidDriveLetters As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        If ValidDriveLetters.IndexOf(DriveLetter) <> -1 Then
            If DriveLetter.Length = 1 Then
                Dim Disk As New System.Management.ManagementObject("Win32_LogicalDisk.DeviceID=""" & DriveLetter & ":""")
                Dim DiskProperty As System.Management.PropertyData
                For Each DiskProperty In Disk.Properties
                    If DiskProperty.Name = "VolumeSerialNumber" Then
                        Return DiskProperty.Value.ToString  '.ToString 'Return the volume serial number. 
                    End If
                Next DiskProperty
            End If
        End If
        Return Nothing 'Invalid drive letter.
    End Function

Open in new window


Author Comment

ID: 24866645
No VOLUME serial number needed. It gets changed by formatting the disk / usb drive.
I am concerned about Hardware/manufacturer serial number that exist in HDDs and USB drives..
LVL 96

Accepted Solution

Bob Learned earned 2000 total points
ID: 24916475
Try this (converted from C# code):

            Dim serialNumber As String = UsbDriveHelper.GetSerialNumberFromDriveLetter("E:")

' Add a reference to the System.Management.dll to the project. 
' Source: 
' http://downloads.cfdan.com/csharp/usbserialnumber.cs.txt 
Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Management
Friend Class UsbDriveHelper
    Public Shared Function GetSerialNumberFromDriveLetter(ByVal driveLetter As String) As String
        If Not driveLetter.EndsWith(":") Then
            driveLetter += ":"
        End If
        Return matchDriveLetterWithSerial(driveLetter)
    End Function
    Private Shared Function matchDriveLetterWithSerial(ByVal driveLetter As String) As String
        Dim serialNumber As String = ""
        Dim searcher1 As New ManagementObjectSearcher("SELECT * FROM Win32_LogicalDiskToPartition")
        For Each dm As ManagementObject In searcher1.[Get]()
            Dim diskArray As String() = Nothing
            Dim currentDrive As String = getValueInQuotes(dm("Dependent").ToString())
            diskArray = getValueInQuotes(dm("Antecedent").ToString()).Split(","c)
            Dim driveNumber As String = diskArray(0).Remove(0, 6).Trim()
            If currentDrive = driveLetter Then
                ' This is where we get the drive serial 
                Dim disks As New ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive")
                For Each disk As ManagementObject In disks.[Get]()
                    If disk("Name").ToString() = ("\\.\PHYSICALDRIVE" & driveNumber) And disk("InterfaceType").ToString() = "USB" Then
                        serialNumber = parseSerialFromDeviceID(disk("PNPDeviceID").ToString())
                    End If
            End If
        Return serialNumber
    End Function
    Private Shared Function parseSerialFromDeviceID(ByVal deviceId As String) As String
        Dim splitDeviceId As String() = deviceId.Split("\"c)
        Dim arrayLen As Integer = splitDeviceId.Length - 1
        Dim serialArray As String() = splitDeviceId(arrayLen).Split("&"c)
        Return serialArray(0)
    End Function
    Private Shared Function getValueInQuotes(ByVal inValue As String) As String
        Dim parsedValue As String = ""
        Dim posFoundStart As Integer = 0
        Dim posFoundEnd As Integer = 0
        posFoundStart = inValue.IndexOf("""")
        posFoundEnd = inValue.IndexOf("""", posFoundStart + 1)
        parsedValue = inValue.Substring(posFoundStart + 1, (posFoundEnd - posFoundStart) - 1)
        Return parsedValue
    End Function
End Class

Open in new window


Author Closing Comment

ID: 31604026
you are Genius indeed. Right on target. As I got a required solution, the question tend to end. I would still desire common code to find HDD, and USB manufacturer's serial number.

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Simulator games are perfect for generating sample realistic data streams, especially for learning data analysis. It is even useful for demoing offerings such as Azure stream analytics, PowerBI etc.
How to fix display issue, screen flickering issue when I plug in power cord to the machine. Before I start explaining the solution lets check out once the issue how it looks like after I connect the power cord. most of you also have faced this…
If you are looking for an automated solution for backup single or multiple Office 365 user mailboxes to Outlook data file, then you can use Kernel Office 365 Backup & Restore tool. Go through the video to check out the steps to backup single or mult…

600 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question