I am trying to find a way to determine the total and available disk space in an arbitrary folder from a .NET app. By \"total disk space\" and \"available disk space\" in a f
Maksim Sestic has given the best answer, as it works on both, local and UNC paths. I have changed his code a little for better error handling and included an example. Works for me like a charm.
You need to put
Imports System.Runtime.InteropServices
into your code, to allow DllImport to be recognized.
Here is the modified code:
_
Private Shared Function GetDiskFreeSpaceEx(lpDirectoryName As String, ByRef lpFreeBytesAvailable As ULong, ByRef lpTotalNumberOfBytes As ULong, ByRef lpTotalNumberOfFreeBytes As ULong) As Boolean
End Function
Public Shared Function GetDriveSpace(folderName As String, ByRef freespace As ULong, ByRef totalspace As ULong) As Boolean
Dim free As ULong = 0
Dim total As ULong = 0
Dim dummy2 As ULong = 0
Try
If Not String.IsNullOrEmpty(folderName) Then
If Not folderName.EndsWith("\") Then
folderName += "\"
End If
If GetDiskFreeSpaceEx(folderName, free, total, dummy2) Then
freespace = free
totalspace = total
Return True
End If
End If
Catch
End Try
Return False
End Function
Call it this way:
dim totalspace as ulong = 0
dim freespace as ulong = 0
if GetDriveSpace("\\anycomputer\anyshare", freespace, totalspace) then
'do what you need to do with freespace and totalspace
else
'some error
end if
The foldername can also be a local directory like drive:\path\path\...
It is still in VB.NET but shouldn't be a problem to translate into C#.