To get a drive serial number in C# and VB.NET you can use the following snippet.

Sample C#

public string GetDriveSerialNumber(string drive)
{
	try
	{
		var driveSerialnumber = string.Empty;
		var pathRoot = Path.GetPathRoot(drive);
		if (pathRoot == null)
		{
			return driveSerialnumber;
		}
		var driveFixed = pathRoot.Replace("\\", "");
		if (driveFixed.Length == 1)
		{
			driveFixed = driveFixed + ":";
		}
		var wmiQuery = string.Format("SELECT VolumeSerialNumber FROM Win32_LogicalDisk Where Name = '{0}'", driveFixed);
		using (var driveSearcher = new ManagementObjectSearcher(wmiQuery))
		{
			using (var driveCollection = driveSearcher.Get())
			{
				foreach (var moItem in driveCollection.Cast<ManagementObject>())
				{
					driveSerialnumber = ConvertHelper.ToString(moItem["VolumeSerialNumber"]);
				}
			}
		}
		return driveSerialnumber;
	}
	catch (Exception ex)
	{
		//handle the error your way
		return string.Empty;
	}
}

Sample VB.NET

Public Function GetDriveSerialNumber(drive As String) As String
	Try
		Dim driveSerialnumber = String.Empty
		Dim pathRoot = Path.GetPathRoot(drive)
		If pathRoot Is Nothing Then
			Return driveSerialnumber
		End If
		Dim driveFixed = pathRoot.Replace("\", "")
		If driveFixed.Length = 1 Then
			driveFixed = driveFixed + ":"
		End If
		Dim wmiQuery = String.Format("SELECT VolumeSerialNumber FROM Win32_LogicalDisk Where Name = '{0}'", driveFixed)
		Using driveSearcher = New ManagementObjectSearcher(wmiQuery)
			Using driveCollection = driveSearcher.Get()
				For Each moItem As var In driveCollection.Cast(Of ManagementObject)()
					driveSerialnumber = ConvertHelper.ToString(moItem("VolumeSerialNumber"))
				Next
			End Using
		End Using
		Return driveSerialnumber
	Catch ex As Exception
		'handle the error your way
		Return String.Empty
	End Try
End Function

One thought on “How to get a drive serial number in C# and VB.NET”

Leave a Reply