[ACCEPTED]-Finding out total and free disk space in .NET-diskspace

Accepted answer
Score: 14

How about this link from MSDN that uses the System.IO.DriveInfo class?

0

Score: 12

You can use GetDiskFreeSpaceEx from kernel32.dll which works with UNC-paths 2 and drives. All you need to do is include 1 a DllImport (see link for an example).

Score: 4

This may not be what you want, but I'm trying 2 to help, and it has the bonus of slightly 1 secure erasing the free space of your drive.

public static string DriveSizeAvailable(string path)
{
    long count = 0;
    byte toWrite = 1;
    try
    {
        using (StreamWriter writer = new StreamWriter(path))
        {
            while (true)
            {
                writer.Write(toWrite);
                count++;
            }
        }
    }
    catch (IOException)
    {                
    }

    return string.Format("There used to be {0} bytes available on drive {1}.", count, path);
}

public static string DriveSizeTotal(string path)
{
    DeleteAllFiles(path);
    int sizeAvailable = GetAvailableSize(path);
    return string.Format("Drive {0} will hold a total of {1} bytes.", path, sizeAvailable);
}
Score: 3

Not really a C# example but may give you 4 a hint - a VB.NET function returning both 3 amount of free and total space on drive 2 (in bytes) along specified path. Works for 1 UNC paths as well, unlike System.IO.DriveInfo.

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 GetDriveSpace(folderName As String, ByRef freespace As ULong, ByRef totalspace As ULong) As Boolean
    If Not String.IsNullOrEmpty(folderName) Then
        If Not folderName.EndsWith("\") Then
            folderName += "\"
        End If

        Dim free As ULong = 0, total As ULong = 0, dummy2 As ULong = 0
        If GetDiskFreeSpaceEx(folderName, free, total, dummy2) Then
            freespace = free
            totalspace = total
            Return True
        End If
    End If
End Function
Score: 1

System.IO.DriveInfo works fine. I'm attached 5 to two separate Netware servers, with several 4 drives mapped.

Here's for the local C: drive:

Drive C:\
  File type: Fixed
  Volume label: Drive C
  File system: NTFS
  Available space to current user:   158558248960 bytes
  Total available space:             158558248960 bytes
  Total size of drive:               249884004352 bytes 

Here's 3 the output for one of the network drives:

Drive F:\
  File type: Network
  Volume label: SYS
  File system: NWFS
  Available space to current user:     1840656384 bytes
  Total available space:               1840656384 bytes
  Total size of drive:                 4124475392 bytes 

I 2 used the following code, directly from the 1 MSDN docs on DriveInfo:

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        DriveInfo[] allDrives = DriveInfo.GetDrives();

        foreach (DriveInfo d in allDrives)
        {
            Console.WriteLine("Drive {0}", d.Name);
            Console.WriteLine("  File type: {0}", d.DriveType);
            if (d.IsReady == true)
            {
                Console.WriteLine("  Volume label: {0}", d.VolumeLabel);
                Console.WriteLine("  File system: {0}", d.DriveFormat);
                Console.WriteLine(
                    "  Available space to current user:{0, 15} bytes", 
                    d.AvailableFreeSpace);

                Console.WriteLine(
                    "  Total available space:          {0, 15} bytes",
                    d.TotalFreeSpace);

                Console.WriteLine(
                    "  Total size of drive:            {0, 15} bytes ",
                    d.TotalSize);
            }
        }
    }
}
Score: 1

Here's one more possibility that I've used 3 for years. The example below is VBScript, but 2 it should work with any COM-aware language. Note 1 that GetDrive() works on UNC shares as well.

Dim Tripped
Dim Level

Tripped = False
Level   = 0

Sub Read(Entry, Source, SearchText, Minimum, Maximum)

    Dim fso
    Dim disk

    Set fso  = CreateObject("Scripting.FileSystemObject")

    Set disk = fso.GetDrive(Source)

    Level = (disk.AvailableSpace / (1024 * 1024 * 1024))

    If (CDbl(Level) < CDbl(Minimum)) or (CDbl(Level) > CDbl(Maximum)) Then
        Tripped = True
    Else
        Tripped = False
    End If

End Sub
Score: 1

Maksim Sestic has given the best answer, as 9 it works on both, local and UNC paths. I 8 have changed his code a little for better 7 error handling and included an example. Works 6 for me like a charm.

You need to put

Imports System.Runtime.InteropServices

into 5 your code, to allow DllImport to be recognized.

Here 4 is the modified code:

<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 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 3 foldername can also be a local directory 2 like drive:\path\path\...

It is still in VB.NET but shouldn't 1 be a problem to translate into C#.

Score: 0

I'm pretty sure this is impossible. In 15 windows explorer, if I try to get the folder 14 properties of a UNC directory, it gives 13 me nothing as far as available space. Used/Available 12 space is a characteristic of drives, not 11 folders, and UNC shares are treated as just 10 folders.

you have to either:
- Map a drive
- Run 9 something on the remote machine to check 8 disk space.

You could also run into problems 7 with something like Distributed file system, in 6 which a UNC/Mapped share is NOT tied to 5 any specific drive, so there youd have to 4 actually sum up several drives.

And what 3 about user quotas? The drive may not be 2 full, but the account you are using to write 1 to that folder may have hit its limit.

Score: 0

Not C# and only gives the avilable space, but 4 . . .

dir \\server\share | find /i "bytes free"

gets you part of the way. I'm looking 3 or the same solution but there doesn't seem 2 to be a nice one - especially when trying 1 to avoid mapping drives.

Score: 0

I just translated VB.NET answers to C#:

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

public static bool GetDriveSpace(string folderName, out ulong freespace, out ulong totalspace)
{
    if (string.IsNullOrEmpty(folderName)) throw new ArgumentNullException(nameof(folderName));
    if (folderName[^1] != '\\') folderName += '\\';
    return GetDiskFreeSpaceEx(folderName, out freespace, out totalspace, out _);
}

0

More Related questions