Finding A Drives Serial Number

.NET still does not expose the drive serial number via the framework. For that you will need to use WMI. Here is the code.

Shared Function GetDriveSerialNumber(ByVal drive As String) As String

    Dim driveSerial As String = String.Empty

 

    ‘No matter what is sent in, get just the drive letter

    Dim driveFixed As String = System.IO.Path.GetPathRoot(drive)

    driveFixed = Replace(driveFixed, “\”, String.Empty)

 

    ‘Perform Query

    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

You will also need to reference System.Management in your project.

Tips By: David McCarter

This code can be found in the open source dotNetTips.Utility assembly


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.