Hi peeps,

Today at work I had an issue with a shared drive on the network which has a quota. So I was wondering how to know if the allowed space is already full or not.

According to my readings on Google, there are only two methods that works for a network drive: WMI or Kernel32 DLL.

Not being a big fan of WMI, I used the Kernel32 here.

public static class DiskHelper
{
    public static long FreeSpace(string folderName)
    {
        if (string.IsNullOrEmpty(folderName))
            throw new ArgumentNullException(nameof(folderName));

        if (!folderName.EndsWith("\\")) folderName += '\\';

        long free = 0, dummy1 = 0, dummy2 = 0;

        if (GetDiskFreeSpaceEx(folderName, ref free, ref dummy1, ref dummy2))
            return free;

        return -1;
    }

    [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressUnmanagedCodeSecurity]
    [DllImport("Kernel32", SetLastError = true, CharSet = CharSet.Auto)]
    [return: MarshalAs(UnmanagedType.Bool)]

    private static extern bool GetDiskFreeSpaceEx
    (
        string lpszPath,                    // Must name a folder, must end with '\'.
        ref long lpFreeBytesAvailable,
        ref long lpTotalNumberOfBytes,
        ref long lpTotalNumberOfFreeBytes
    );
}

And now you can use it like this:

var folderPath = @"\\test\MyProject";
var availableSpace = DiskHelper.FreeSpace(folderPath);

Happy coding!  🙂