How to check if IOException is Not-Enough-Disk-Space-Exception type?

You need to check the HResult and test against ERROR_DISK_FULL (0x70) and ERROR_HANDLE_DISK_FULL (0x27), which can be converted to HResults by OR‘ing with 0x80070000.

For .Net Framework 4.5 and above, you can use the Exception.HResult property:

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

For older versions, you can use Marshal.GetHRForException to get back the HResult, but this 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;
}

From the MSDN documentation:

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.

See also How do I determine the HResult for a System.IO.IOException?

Leave a Comment

tech