Your call to GetLastError
returns 0
because there are other APIs called after CreateFile
returns, and your exception code executes.
The error code returned by GetLastError
a thread local variable and is shared between all code that runs in your thread. So in order to capture the error code you need to call GetLastError
immediately after the failed function returns.
The documentation explains it like this:
Functions executed by the calling thread set this value by calling the SetLastError function. You should call the GetLastError function immediately when a function's return value indicates that such a call will return useful data. That is because some functions call SetLastError with a zero when they succeed, wiping out the error code set by the most recently failed function.
If you are using TFileStream.Create
then the framework doesn't give you an opportunity to call GetLastError
at the suitable moment. If you really want to get that information you will have to call CreateFile
yourself and use a THandleStream
instead of TFileStream
.
The idea there is that with THandleStream
you are responsible for the synthesis of the file handle which you pass to the constructor of THandleStream
. That gives you the opportunity to capture the error code in case of failure.