Reputation: 1262
I'm curious if there is a function in C#
to convert an Win32 HRESULT (long)
error code gotten from unmanaged code into the representation string
.
Upvotes: 1
Views: 1552
Reputation: 21956
I’m not aware of a single function but the workaround is easy enough.
public static string formatMessage( int hr ) =>
Marshal.GetExceptionForHR( hr ).Message;
Update: the “duplicate” question is very different.
HRESULT codes are documented in section 2.1 of the [MS-ERREF] spec.
Any Win32 code can be packed into HRESULT, by using Severity=1 and Facility=FACILITY_WIN32. The opposite is not true, FACILITY_WIN32 is just one of the many. The accepted answer to the “duplicate” question, which uses Win32Exception
, doesn’t apply to this question.
Here's a quick demo.
static void testHresultMessages()
{
int hr = new OverflowException().HResult;
// Prints "Unknown error (0x80131516)"
Console.WriteLine( new Win32Exception( hr ).Message );
// Prints "Arithmetic operation resulted in an overflow."
Console.WriteLine( Marshal.GetExceptionForHR( hr ).Message );
}
Upvotes: 4