สำหรับ Net.Core ภายใต้ Linux คุณสามารถโทรได้
var freeBytes = new DriveInfo(path).AvailableFreeSpace;
โดยที่ path คือชื่อโฟลเดอร์แบบสัมพัทธ์หรือแบบสัมบูรณ์ และจะให้ข้อมูลไดรฟ์เกี่ยวกับพาร์ติชันที่เก็บพาธนี้แก่คุณโดยอัตโนมัติ ทดสอบบน Net.Core 2.2
ในทางตรงกันข้าม ใน Windows คุณ:
A) จำเป็นต้องจัดเตรียมอักษรระบุไดรฟ์ (ซึ่งน่าเสียดายที่ไม่สามารถรับมาจากเส้นทางสัมพัทธ์ได้โดยตรง ดังนั้นคุณต้องทำงานเพิ่มเติม และไม่สามารถคำนวณสำหรับเส้นทาง UNC ได้เลย)
B) จำเป็นต้องใช้ Windows API (ใช้ได้กับเส้นทาง 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 __);
นอกจากนี้ยังมีบางกรณีพิเศษอื่น ๆ ดังนั้นในที่สุดการใช้งานของฉันก็มีลักษณะดังนี้:
#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