Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out Free and Total space on a network unc path in netcore 3.x

I am updating an application that previously used AlphaFS to provide IO operations for local and network paths.

One of the functions is to return drive free and available space. This works fine if the drive is local or mapped using DriveInfo

 var pathRoot = System.IO.Path.GetPathRoot(startPath);
 var driveInfo = new DriveInfo(pathRoot);
 AvailSpace = (ulong) driveInfo.AvailableFreeSpace;
 TotalSpace = (ulong) driveInfo.TotalSize;

but for an unc path it will error with

Drive name must be a root directory (i.e. 'C:\') or a drive letter ('C').

Is there a suitable alternative to DriveInfo that can be used for network unc paths in .NET Core 3.x?

like image 519
Jafin Avatar asked Nov 03 '25 07:11

Jafin


1 Answers

If your application only runs on Windows, you could try GetDiskFreeSpaceEx, which the MSDN docs says it supports UNC path.

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

GetDiskFreeSpaceEx("\\\\server\\path\\", out var size, out var _, out var __);
like image 84
weichch Avatar answered Nov 05 '25 22:11

weichch