Aug 24 2010
Get a Helpful Error Message from WinErrors.h in C#
It’s been a while since I’ve posted something like this, but this is one of those things that did not show up under the search terms I thought to be appropriate. Hopefully this post will get sorted to the top of the search terms I was using.
The problem is that when you call into Win32 APIs from managed C# code, they often return a simple integer to inform you of the status of your invocation. Zero means success, and everything greater than zero corresponds to one of the many many WinErrors.h error codes. Of course, you could hard-code these helpful messages into your code, but this is bad for various reasons. Thanksfully, .NET provides you with the Marshal.GetExceptionFromHR() method to dynamically query any helpful error message you may need!
The pluralsight blog shows how to wrap this up into a nice set of functions:
static string getWin32ErrorMessage(int errorCode) {
int hr = HRESULT_FROM_WIN32(errorCode);
Exception x = Marshal.GetExceptionForHR(hr);
return x.Message;
}
static int HRESULT_FROM_WIN32(int errorCode) {
if (errorCode <= 0) return errorCode;
return (int)((0x0000FFFFU &
((uint)errorCode)) | (7U << 16) |
0x80000000U);
}