Finding out total and free disk space in .NET

前端 未结 9 1245
我在风中等你
我在风中等你 2021-01-04 03:08

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

9条回答
  •  日久生厌
    2021-01-04 03:42

    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#.

提交回复
热议问题