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

One thought on “How to get free Drive Space in C# and VB.NET”

Leave a Reply