How to get free Drive Space in C# and VB.NET

To get free Drive Space in C# and VB.NET you can use the following snippet.

Sample C#

[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetDiskFreeSpaceEx(string lpDirectoryName,out ulong lpFreeBytesAvailable,out ulong lpTotalNumberOfBytes,out ulong lpTotalNumberOfFreeBytes);

public static bool GetFreeDriveSpace(string path, out ulong freebytes)
{
	if (string.IsNullOrEmpty(path))
	{
		throw new ArgumentNullException("path");
	}

	if (!path.EndsWith("\\"))
	{
		path = String.Concat(path, "\\");
	}

	ulong lpFreeBytesAvailable;
	ulong lpTotalNumberOfBytes;
	ulong lpTotalNumberOfFreeBytes;

	if (GetDiskFreeSpaceEx(path, out lpFreeBytesAvailable, out lpTotalNumberOfBytes, out lpTotalNumberOfFreeBytes))
	{
		freebytes = lpFreeBytesAvailable;
		return true;
	}
	freebytes = 0;
	return false;
}

Sample VB.NET

<DllImport("kernel32.dll", SetLastError := True, CharSet := CharSet.Auto)> _
Private Shared Function GetDiskFreeSpaceEx(lpDirectoryName As String, ByRef lpFreeBytesAvailable As ULong, ByRef lpTotalNumberOfBytes As ULong, ByRef lpTotalNumberOfFreeBytes As ULong) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function

Public Shared Function GetFreeDriveSpace(path As String, ByRef freebytes As ULong) As Boolean
	If String.IsNullOrEmpty(path) Then
		Throw New ArgumentNullException("path")
	End If

	If Not path.EndsWith("\") Then
		path = [String].Concat(path, "\")
	End If

	Dim lpFreeBytesAvailable As ULong
	Dim lpTotalNumberOfBytes As ULong
	Dim lpTotalNumberOfFreeBytes As ULong

	If GetDiskFreeSpaceEx(path, lpFreeBytesAvailable, lpTotalNumberOfBytes, lpTotalNumberOfFreeBytes) Then
		freebytes = lpFreeBytesAvailable
		Return True
	End If
	freebytes = 0
	Return False
End Function

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

How to open cd rom drives in VBScript

To open cd rom drives in VBScript you can use the following snippet.

Sample VBScript

Set wmPlayer = CreateObject("WMPlayer.OCX.7" )
Set colDrives = wmPlayer.cdromCollection

if colDrives.Count >= 1 then
        For i = 0 to colDrives.Count - 1
			colDrives.Item(i).Eject
        Next
End If

How to get free disk space in C# and VB.NET

To get free disk space in C# and VB.NET you can use the following snippet.

Sample C#

[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetDiskFreeSpaceEx(string lpDirectoryName, out ulong lpFreeBytesAvailable, out ulong lpTotalNumberOfBytes,out ulong lpTotalNumberOfFreeBytes);

public static bool GetFreeBytes(string folderName, out ulong freeBytes)
{
	freeBytes = 0;
	if (!folderName.EndsWith("\\"))
	{
		folderName += '\\';
	}
	ulong freeSpaceInBytes = 0;
	ulong notUsed = 0;
	ulong notUsed2 = 0;
	if (GetDiskFreeSpaceEx(folderName, out freeSpaceInBytes, out notUsed, out notUsed2))
	{
		freeBytes = freeSpaceInBytes;
		return true;
	}
	else
	{
		return false;
	}
}

Sample VB.NET

<DllImport("kernel32.dll", SetLastError := True, CharSet := CharSet.Auto)> _
Public Shared Function GetDiskFreeSpaceEx(lpDirectoryName As String, ByRef lpFreeBytesAvailable As ULong, ByRef lpTotalNumberOfBytes As ULong, ByRef lpTotalNumberOfFreeBytes As ULong) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function

Public Shared Function GetFreeBytes(folderName As String, ByRef freeBytes As ULong) As Boolean
	freeBytes = 0
	If Not folderName.EndsWith("\") Then
		folderName += "\"
	End If
	Dim freeSpaceInBytes As ULong = 0
	Dim notUsed As ULong = 0
	Dim notUsed2 As ULong = 0
	If GetDiskFreeSpaceEx(folderName, freeSpaceInBytes, notUsed, notUsed2) Then
		freeBytes = freeSpaceInBytes
		Return True
	Else
		Return False
	End If
End Function