Handling COM Error Codes
Sometimes COM Objects return a HRESULT that is outside of the bounds of a C# integer.
Unfortunately, the only way to correctly handle a COM Exception in .NET is to use the ComException Class. But if the HRESULT isn’t an Int, and the ErrorCode Property on the ComException class is an Int, how are you supposed to ever be able to catch that specific HRESULT?
Fear not! Here’s how to handle a COM ErrorCode that can’t be converted to an Int (in this example, it’s unsigned)
-
{
-
_PropertyHandler.Open(filePath, false, dsoFileOpenOptions.dsoOptionDefault);
-
}
-
catch (COMException comEx)
-
{
-
if (comEx.ErrorCode == unchecked((int)0×800300FC))
-
{
-
throw new FileNotFoundException("Could not find file:");
-
}
-
}
The magic happens in the ‘unchecked’ statement - which tells the compiler not to perform the overflow-checking context for integral-type arithmetic operations and conversions.
More on the Unchecked Operator over on MSDN.