Dealing with Win32 Errors

suggest change

When using interop methods, you can use GetLastError API to get additional information on you API calls.

DllImport Attribute SetLastError Attribute

SetLastError=true

Indicates that the callee will call SetLastError (Win32 API function).

SetLastError=false

Indicates that the callee will not call SetLastError (Win32 API function), therefore you will not get an error information.

Example:

[DllImport("kernel32.dll", SetLastError=true)]
public static extern IntPtr OpenMutex(uint access, bool handle, string lpName);

If you trying to open mutex which does not exist, GetLastError will return ERROR_FILE_NOT_FOUND.

var lastErrorCode = Marshal.GetLastWin32Error();

if (lastErrorCode == (uint)ERROR_FILE_NOT_FOUND)
{
    //Deal with error         
}

System Error Codes can be found here:

https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx

GetLastError API

There is a native GetLastError API which you can use as well :

[DllImport("coredll.dll", SetLastError=true)]
static extern Int32 GetLastError();

Here’s why:

Between your Win32 call which sets the error (calls SetLastError), the CLR can call other Win32 calls which could call SetLastError as well, this behavior can override your error value. In this scenario, if you call GetLastError you can obtain an invalid error.

Setting SetLastError = true, makes sure that the CLR retrieves the error code before it executes other Win32 calls.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Interoperability:
* Dealing with Win32 Errors

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script
149 Interoperability