public static Exception Unwrap(Exception error) {
for(;;) {
var invocationException = error as TargetInvocationException;
if(invocationException != null)
error = invocationException.InnerException;
var innerExceptionsProp = error.GetType().GetProperty("InnerExceptions", BindingFlags.Instance | BindingFlags.Public);
if(innerExceptionsProp == null)
return error;
var innerExceptions = innerExceptionsProp.GetValue(error, null) as ICollection<Exception>;
if(innerExceptions != null && innerExceptions.Count == 1)
error = innerExceptions.First();
else return error;
}
}