How to check if IOException is Not-Enough-Disk-Space-Exception type?-Collection of common programming errors
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.