c# - 如何检查 IOException 是否为 Not-Enough-Disk-Space-Exception 类型?

标签 c# .net exception-handling ioexception diskspace

如何检查 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/

相关文章:

C# 没有从非托管 C++ dll 中捕获未处理的异常

c# - 串行端口 Port.Write() 命令

c# - IDbConnection Open 挂起 C#

c# - 为什么我*不*在 VS2008 的单元测试中收集代码覆盖率数据?

c# - 如何使用文件路径从 csproj 文件访问 Azure 开发操作存储库中保存的文件?

c# - 使用相同的名称/命名空间实例化不同的类

spring - @RestControllerAdvice 和 @ControllerAdvice 在一起

c# - 在类型上找不到匹配的构造函数

c# - 如何删除复杂 json 对象中的空字符串 json 值?

c# - 获取对象列表的 MVC 客户端验证的完整属性名称