C# Windows 窗体:尝试将文件复制到远程计算机时检测其硬盘驱动器是否已满。系统.IO IOException

问题描述 投票:0回答:1

在我的公司,我们长期面临着小型 SSD 的填充问题。有时 SSD (HD) 已满,从网络复制到其中时无法容纳 2KB 文件。

System.IO
会抛出错误:

IO异常:磁盘空间不足

我想捕获全高清

IOException
并尝试远程删除
C:\Windows\Temp
目录以打开硬盘空间以进行进一步的磁盘清理维护。

我写了以下内容来观看全高清

IOException
;我无法测试是否成功,因为我没有可以测试全高清的客户端。

下面的代码可以工作吗?

catch (IOException ioEX) when (ioEX.Message == "There is not enough space on the disk.")
{
    try
    {
        string remoteWindowsTemp = @"\\" + computerName + @"\C$\Windows\Temp";

        // Attempt to clear off HD space directly from local computer
        Directory.Delete(remoteWindowsTemp, true);
    }
    catch 
    {  
        // ...Other IO conditions I have written that I know work... }
    }
}

enter image description here

c# winforms ioexception
1个回答
0
投票

您可以从内核调用

GetDiskFreeSpaceEx
函数,并将其用于网络位置:

[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
static extern bool GetDiskFreeSpaceEx(string lpDirectoryName, out ulong lpFreeBytesAvailable, out ulong lpTotalNumberOfBytes, out ulong lpTotalNumberOfFreeBytes);

bool HasEnoughSpace(string srcFile, string destPath) {
  var fileBytes = (ulong)(new FileInfo(srcFile).Length);
  GetDiskFreeSpaceEx(destPath, out var availableBytes, out _, out _);

  return fileBytes <= availableBytes;
}

if (!HasEnoughSpace(@"C:\MyFile.txt", @"\\127.0.0.1\C$")) {
  // Clear some space
}


-或-

如果您确实采取了捕获异常的方式,则匹配某些魔术字符串通常会很糟糕,因为它受区域设置的影响,并且不能保证在操作系统更新时不会更改。最好通过错误码来匹配。在这种特殊情况下,错误是

ERROR_DISK_FULL
(0x70)

IOException
中,系统错误代码附加到其
HResult

const int ERROR_DISK_FULL = 0x70;

try {

} catch (IOException ex) when (ex.HResult == ERROR_DISK_FULL) {
  // Clear some space
}
© www.soinside.com 2019 - 2024. All rights reserved.