Win32Exception class forgotten
It’s very common to see people (and books) declaring the FormatMessage Win32 API function in .NET in order to get the message of the Last Win32 Error Code.
In .NET, if you want to get the message error of the error code returned by the last unmanaged function called using Platform Invoke, use:
String message = (new System.ComponentModel.Win32Exception()).Message;
Instead of P/Invoke the FormatMessage Win32 API function, like:
[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
static extern int FormatMessage(int dwFlags,ref IntPtr lpSource,
int dwMessageId,int dwLanguageId,ref String lpBuffer,int nSize,
IntPtr Arguments)
Even the Microsoft Configuration Management Application Block for .NET (http://msdn.microsoft.com/library/en-us/dnbda/html/cmab.asp) declares FormatMessage in its DataProtection class and uses the following code instead of writing a simple line (new Win32Exception()).Message :
private static String GetErrorMessage(int errorCode)
{
int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100;
int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
int messageSize = 255;
String lpMsgBuf = "";
int dwFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER FORMAT_MESSAGE_FROM_SYSTEM FORMAT_MESSAGE_IGNORE_INSERTS;
IntPtr ptrlpSource = new IntPtr();
IntPtr prtArguments = new IntPtr();
int retVal = FormatMessage(dwFlags, ref ptrlpSource, errorCode, 0, ref lpMsgBuf, messageSize, IntPtr.Zero );
if(0 == retVal)
{
throw new Exception( Resource.ResourceManager[ "Res_ExceptionFormattingMessage", errorCode ] );
}
return lpMsgBuf;
}
