0

I am using GetDriveSerialNumber() to retrieve drive volume serial number in visual basic 2010.

I have the following imports:

Imports System
Imports System.IO
Imports System.Text
Imports System.Net.NetworkInformation
Imports System.Management
Imports System.Collections
Imports Microsoft.Win32
Imports Microsoft.VisualBasic

And then in the Module:

Dim path As String

   'Get HD volume Serial Number from Function
        Dim DriveVID As String = GetDriveSerialNumber()

The function is:

'Get HD Volume serial Number
Public Function GetDriveSerialNumber() As String
    Dim DriveSerial As Long
    Dim fso As Object, Drv As Object
    'Create a FileSystemObject object
    fso = CreateObject("Scripting.FileSystemObject")
    Drv = fso.GetDrive(fso.GetDriveName(AppDomain.CurrentDomain.BaseDirectory))
    With Drv
        If .IsReady Then
            DriveSerial = .SerialNumber
        Else    '"Drive Not Ready!"
            DriveSerial = -1
        End If
    End With
    'Clean up
    Drv = Nothing
    fso = Nothing
    GetDriveSerialNumber = Hex(DriveSerial)
End Function

This works great for 9 out 10 computers,

Only one gives me back a different 7 characters,

Oppose to the 8 characters it should give me,

Even when I type vol command in cmd,

On that computer,

It gives me the correct 8 characters volume serial number,

Does anyone know what’s wrong?

user2333346
  • 1,083
  • 4
  • 21
  • 40

1 Answers1

0

This Function seems to work with all my test computers:

Private Function GetDriveSerialNumber(ByVal drive As String) As String
    Dim driveSerial As String = String.Empty
    Dim driveFixed As String = Path.GetPathRoot(drive)

    driveFixed = Replace(driveFixed, "\", String.Empty)

    Using querySearch As New ManagementObjectSearcher("SELECT VolumeSerialNumber FROM Win32_LogicalDisk Where Name = '" & driveFixed & "'")
        Using queryCollection As ManagementObjectCollection = querySearch.Get()
            Dim moItem As ManagementObject
            For Each moItem In queryCollection

                driveSerial = CStr(moItem.Item("VolumeSerialNumber"))

                Exit For
            Next
        End Using
    End Using

    Return driveSerial
End Function

The only thing is that you have to send a drive letter to the Function, Which is not a problem with me,

user2333346
  • 1,083
  • 4
  • 21
  • 40