Untuk Net.Core di Linux Anda cukup menelepon
var freeBytes = new DriveInfo(path).AvailableFreeSpace;
di mana jalur adalah nama folder relatif atau absolut, dan secara otomatis memberi Anda informasi drive tentang partisi yang menyimpan jalur ini. Diuji pada Net.Core 2.2.
Sebaliknya, di Windows Anda:
A) Perlu memberikan huruf drive (yang sayangnya tidak dapat diturunkan langsung dari jalur relatif, jadi Anda perlu melakukan beberapa pekerjaan tambahan, dan tidak dapat dihitung untuk jalur UNC sama sekali).
B) Perlu menggunakan Windows API (ini juga berfungsi dengan jalur UNC):
[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(path, out var freeBytes, out var _, out var __);
Ada juga beberapa kasus luar biasa lainnya sehingga pada akhirnya penggunaan saya terlihat seperti berikut:
#if DEBUG
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetDiskFreeSpaceEx(string lpDirectoryName,
out long lpFreeBytesAvailable,
out long lpTotalNumberOfBytes,
out long lpTotalNumberOfFreeBytes);
#endif
public long? CheckDiskSpace()
{
long? freeBytes = null;
try
{
#if DEBUG //RuntimeInformation and OSPlatform seem to not exist while building for Linux platform
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
long freeBytesOut;
//On some drives (for example, RAM drives, GetDiskFreeSpaceEx does not work
if (GetDiskFreeSpaceEx(_path, out freeBytesOut, out var _, out var __))
freeBytes = freeBytesOut;
}
#endif
if (freeBytes == null)
{
//DriveInfo works well on paths in Linux //TODO: what about Mac?
var drive = new DriveInfo(_path);
freeBytes = drive.AvailableFreeSpace;
}
}
catch (ArgumentException)
{
//ignore the exception
}
return freeBytes;
}
person
Roland Pihlakas
schedule
18.07.2020