如何检查 IOException
是否为“磁盘空间不足”异常类型?
目前我检查消息是否匹配“磁盘空间不足”之类的内容,但我知道如果操作系统语言不是英语,这将不起作用。
最佳答案
您需要检查 HResult
并根据 ERROR_DISK_FULL (0x70) 进行测试和 ERROR_HANDLE_DISK_FULL (0x27) ,这can be converted to HResults
by OR
'ing with 0x80070000
.
对于 .Net Framework 4.5 及更高版本,您可以使用 Exception.HResult
属性:
static bool IsDiskFull(Exception ex)
{
const int HR_ERROR_HANDLE_DISK_FULL = unchecked((int)0x80070027);
const int HR_ERROR_DISK_FULL = unchecked((int)0x80070070);
return ex.HResult == HR_ERROR_HANDLE_DISK_FULL
|| ex.HResult == HR_ERROR_DISK_FULL;
}
对于旧版本,您可以使用 Marshal.GetHRForException
取回 HResult,但是这个 has significant side-effects and is not recommended :
static bool IsDiskFull(Exception ex)
{
const int ERROR_HANDLE_DISK_FULL = 0x27;
const int ERROR_DISK_FULL = 0x70;
int win32ErrorCode = Marshal.GetHRForException(ex) & 0xFFFF;
return win32ErrorCode == ERROR_HANDLE_DISK_FULL || win32ErrorCode == ERROR_DISK_FULL;
}
来自 MSDN 文档:
Note that the GetHRForException method sets the IErrorInfo of the current thread. This can cause unexpected results for methods like the ThrowExceptionForHR methods that default to using the IErrorInfo of the current thread if it is set.
另见 How do I determine the HResult for a System.IO.IOException?
关于c# - 如何检查 IOException 是否为 Not-Enough-Disk-Space-Exception 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9293227/