Get a disk's serial number
By: Rick Rothstein Date: 23/06/2000

Each time a disk is formatted, the operationg system assigns a 32-bit number that can be considered unique. That is the disk's serial number.

Start with adding the following API Declarations to the Declarations section of a form/module:

Private Declare Function GetVolumeInformation Lib _
"kernel32.dll" Alias "GetVolumeInformationA" (ByVal _
lpRootPathName As String, ByVal lpVolumeNameBuffer As _
String, ByVal nVolumeNameSize As Integer, _
lpVolumeSerialNumber As Long, lpMaximumComponentLength _
As Long, lpFileSystemFlags As Long, ByVal _
lpFileSystemNameBuffer As String, ByVal _
nFileSystemNameSize As Long) As Long

Now, paste the following Function into the same form/module:

Function GetSerialNumber(DriveLetter As String) As String
    Dim SerialNum As Long
    Dim VolNameBuf As String
    Dim FileSysNameBuf As String
    Select Case Len(DriveLetter)
        Case 1
            If LCase(DriveLetter) Like "[a-z]" Then
                DriveLetter = Left(DriveLetter, 1) & ":\"
            Else
                GetSerialNumber = "Error - Bad drive designation"
            End If
        Case 2
            If LCase(DriveLetter) Like "[a-z]:" Then
                DriveLetter = DriveLetter & "\"
            Else
                GetSerialNumber = "Error - Bad drive designation"
            End If
        Case 3
            If LCase(DriveLetter) Like "[!a-z]:\" Then
                GetSerialNumber = "Error - Bad drive designation"
            End If
        Case Else
            GetSerialNumber = "Error - Bad drive designation"
    End Select
    If Len(GetSerialNumber) = 0 Then
        VolNameBuf = String(255, Chr(0))
        FileSysNameBuf = String(255, Chr$(0))
        GetVolumeInformation DriveLetter, VolNameBuf, _
         Len(VolNameBuf), SerialNum, 0, 0, _
         FileSysNameBuf, Len(FileSysNameBuf)

        GetSerialNumber = Right("00000000" & Hex(SerialNum), 8)
    End If
End Function

Once you've done the above, the use of the function is simple. The following instruction pops-up a box with drive C serial number:

MsgBox GetSerialNumber("C:")

Instead of "C:", you can type "C:\" or just "C": all forms are accepted!

The serial number will be shown in hex, as it is usually viewed. If you prefer to see it as a long number, replace the 3rd-last line of the code with the following:

GetSerialNumber = SerialNum

Thanks to Rick Rothstein for the posting of this useful tip!

Click Here!


Visual Basic Programming Zone is a website by Lorenzo Dalla Vecchia.
To contact the Webmaster, click here.
Hosted by InWind: www.inwind.it