How to get the system drives in C# and VB.NET

To get the system drives in C# and VB.NET you can use the following snippet.

Sample C#

public static DriveInfo[] GetDrives(bool runningDrivesOnly)
{
	return runningDrivesOnly ? Enumerable.Cast<DriveInfo>(DriveInfo.GetDrives()).Where(x => x.IsReady).ToArray() : DriveInfo.GetDrives();
}

Sample VB.NET

Public Shared Function GetDrives(runningDrivesOnly As Boolean) As DriveInfo()
	Return If(runningDrivesOnly, Enumerable.Cast(Of DriveInfo)(DriveInfo.GetDrives()).Where(Function(x) x.IsReady).ToArray(), DriveInfo.GetDrives())
End Function

How to get a drive serial number in C# and VB.NET

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