Dot*_*Dev 8 c# .net-core asp.net-core
有没有办法使用 C# ASP.NET Core 在不同的操作系统(主要是 Linux 和 Windows)上找到可用空间。
我找到了一种方法(使用 DriveInfo)通过将驱动器名称作为参数传递来获得可用空间。这在 Windows 上运行良好,但我也希望在 Linux 上也是如此。
public static int CheckDiskSpace(string driveLetter)
{
DriveInfo drive = new DriveInfo(driveLetter);
var totalBytes = drive.TotalSize;
var freeBytes = drive.AvailableFreeSpace;
var freePercent = (int)((100 * freeBytes) / totalBytes);
return freePercent;
}
Run Code Online (Sandbox Code Playgroud)
传递驱动器 (C:/) 如下:
var freespace = DriveDetails.CheckDiskSpace("C:/");
Run Code Online (Sandbox Code Playgroud)
更新:这也适用于 Linux。
对于 Linux 下的 Net.Core,您只需调用
var freeBytes = new DriveInfo(path).AvailableFreeSpace;
Run Code Online (Sandbox Code Playgroud)
其中 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 __);
Run Code Online (Sandbox Code Playgroud)
还有一些其他特殊情况,所以最后我的用法如下所示:
#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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3346 次 |
| 最近记录: |