如何检查是否IOException异常不-足够磁盘空间,异常类型?异常、磁盘空间、类型、IOException

2023-09-02 21:22:47 作者:孤久成瘾

我如何检查是否 IOException异常是一个没有足够的磁盘空间类型的异常?

How can I check if IOException is a "Not enough disk space" exception type?

目前,我检查,看看是否与消息相匹配的东西,如磁盘空间不足,但我知道,这是行不通的,如果操作系统语言不是英语。

At the moment I check to see if the message matches something like "Not enough disk space", but I know that this won't work if the OS language is not English.

推荐答案

您需要检查对ERROR_DISK_FULL (0x70)和ERROR_HANDLE_DISK_FULL (0x27)

You need to check the HResult and test against ERROR_DISK_FULL (0x70) and ERROR_HANDLE_DISK_FULL (0x27)

要获得HResult的一个例外,使用Marshal.GetHRForException

To get the HResult for an exception use Marshal.GetHRForException

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;
}

注意 GetHRForException 有副作用,从MSDN文档:

Note that GetHRForException has a side effect, from the MSDN documentation:

注意 GetHRForException 方式设置的IErrorInfo   当前线程。这可能会导致意想不到的结果,如方法   ThrowExceptionForHR方法是默认使用的IErrorInfo的   如果它被设置当前线程

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我确定HResult的一个System.IO.IOException?