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

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

Leave a Reply