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

前端 未结 5 1504
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 06:12

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 e

5条回答
  •  广开言路
    2020-11-28 07:00

    Well, it's a bit hacky, but here we go.

    First thing to do is to get the HResult from the exception. As it's a protected member, we need a bit of reflection to get the value. Here's an extension method to will do the trick:

    public static class ExceptionExtensions
    {
        public static int HResultPublic(this Exception exception)
        {
            var hResult = exception.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance).Where(z => z.Name.Equals("HResult")).First();
            return (int)hResult.GetValue(exception, null);
        }
    }
    

    Now, in your catch scope, you can get the HResult:

    catch (Exception ex)
    {
        int hResult = ex.HResultPublic();
    }
    

    From here, you'll have to interpret the HResult. You'll need this link.

    We need to get the ErrorCode which is stored in the 16 first bits of the value, so here's some bit operation:

    int errorCode = (int)(hResult & 0x0000FFFF);
    

    Now, refer to the list of system error codes and here we are:

    ERROR_DISK_FULL
    112 (0x70)
    

    So test it using:

    switch (errorCode)
    {
        case 112:
            // Disk full
    }
    

    Maybe there are some "higher level" functions to get all this stuff, but at least it works.

提交回复
热议问题