Skip to content

Instantly share code, notes, and snippets.

@xiaomi7732
Last active February 23, 2023 22:30
Show Gist options
  • Select an option

  • Save xiaomi7732/c097c89e4fdf1bf8923c302bcf553930 to your computer and use it in GitHub Desktop.

Select an option

Save xiaomi7732/c097c89e4fdf1bf8923c302bcf553930 to your computer and use it in GitHub Desktop.
Get proper disk space for mounted volume

This siutation is encountered in Azure Function where we want to have telemetries for available space for temp as well as home. It is a general issue of getting available space for mounted folder.

See the result, notice the difference between using different ways to get free space for the same folder? Why? image

Assuming temp folder location: c:\users\abc\temp, disk c has 1G free, and temp is mounted from another volume that has 5G.

This gets the free disk space for the driver, not for the mounted folder - 1G:

ulong availableSpace = GetDiskFreeSpace(tempFolder);

And this gets the actual available space for the mount point (5G):

[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetDiskFreeSpaceEx(string lpDirectoryName,
    out ulong lpFreeBytesAvailable,
    out ulong lpTotalNumberOfBytes,
    out ulong lpTotalNumberOfFreeBytes);

private static ulong GetDiskFreeSpace(string path)
{
    // Making sure there's tailing slash.
    // Refer to https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getdiskfreespaceexa
    path = path.TrimEnd('\\') + '\\';

    if (string.IsNullOrEmpty(path))
    {
        throw new ArgumentNullException(nameof(path));
    }

    if (!GetDiskFreeSpaceEx(path, out ulong freeSpace, out _, out _))
    {
        throw new Win32Exception(Marshal.GetLastWin32Error());
    }

    return freeSpace;
}

Notice it was a PInvoke on Win32 API, means it won't work on Linux.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment