Welcome to MSDN Blogs Sign in | Join | Help

FormatMessage Shortcut for Win32 Error Codes

If you ever need to P/Invoke to an API that returns extended error information via the GetLastError function, then you've also probably been through the pain of converting the error code into a usable error message via the FormatMessage API  ... not exactly one of the more user-friendly APIs for managed code callers.

Thankfully, there's a shortcut way to get this message, exposed through the Win32Exception class.  Simply doing this:

string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message;

Will prevent you from needing to call FormatMessage to get an error message for an error code.

Of course you also need to remember to set the SetLastError named parameter on your DllImport attribute to true, and obtain the error code through a call to Marshal.GetLastWin32Error, since P/Invoking to GetLastError directly will generally not work (since the last error may have been set again by another API that the CLR has called).  If you're using VB.Net, Err.LastDllError is also an acceptable way of accessing the last error code.

Published Friday, September 10, 2004 11:32 AM by shawnfa
Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: FormatMessage Shortcut for Win32 Error Codes

Sunday, September 12, 2004 1:15 AM by Evgeny M
Something in the area, related to ComExceptions.
To retrieve hresult from com exception use:
uint HResult = (uint)Marshal.GetHRForException(ex);

# re: FormatMessage Shortcut for Win32 Error Codes

Thursday, July 28, 2005 11:13 AM by Richard
Actually, you can simplify the call to:

string errorMessage = new Win32Exception().Message;

The default constructor for the Win32Excpeption calls Marshall.GetLastWin32Error for you.

# re: FormatMessage Shortcut for Win32 Error Codes

Thursday, July 28, 2005 8:28 PM by shawnfa
Good point Richard -- thanks for the tip.

-Shawn

# re: FormatMessage Shortcut for Win32 Error Codes

Friday, January 05, 2007 1:06 AM by jholder

One good thing I wanted to point out about writing it this way (at least for learning purposes):

string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message;

is that it is obvious I can stick an int in there and get out the message:

int errcode = somefunction();

string errorMessage = new Win32Exception(errcode).Message;

Just a quick observation.

Leave a Comment

(required) 
required 
(required) 
 
Page view tracker