When I execute this code without runtime packages, I have a 32 code error, that is correct. But when I activite runtime packages (for exemple just with "FireDACASADriver;YmagControlDB") the error code is always "0"
procedure TForm1.Button1Click(Sender: TObject);
Var
Stream: TStream;
iError : integer;
begin
Stream := nil;
iError := -1;
try
try
Stream := TFileStream.Create('d:\toto.docx', fmOpenRead);
except
begin
iError := GetLastError;
end;
end;
finally
if Assigned(Stream) then
Stream.Free;
end;
showmessage('Erreur : ' + inttostr(iError));
end;
How I can fix the GetLastError with runtime packages ?
It is simply not appropriate to call
GetLastErrorthere. You are mixing two different error handling models.Call
GetLastErrorimmediately after an API call fails, if the documentation says to do so. When you call it, something other function could very well have calledSetLastErrorand reset the value.So it is wrong to call
GetLastErrorsince you aren't using Win32 functions, and should remove the call toGetLastError. Your code should be:If there is an error, an exception will be raised which will be reported by the top level exception handler.
Runtime packages should have no bearing on how this code executes.
Possible causes of an error are that the file does not exist, or that it is locked.
You wrote:
That is always pointless since the
Freemethod also checks for the object reference beingnil. In fact your code is equivalent to:So it is cleaner to rely on test inside
Freeand simply write:In the comments you state that you actually want to test whether or not the file is locked. Don't use a file stream for that. Instead do the following:
CreateFileto open the file.INVALID_HANDLE_VALUEto detect error.GetLastErrorto find out the cause of error.CloseHandle.However, this is not to be recommended. You might use this approach to determine that the file is not locked, but by the time you try to read it, it has been locked. There is an inherent race condition.
As a general guideline it is better to ask forgiveness than permission.