Reliable method for checking that an online file exists

  

I have the following code which checks that a file exists on a website. Sometimes it works and sometimes it doesn’t. When it doesn’t work it invokes EIdHTTPProtocolException and returns 0 even though the file is present on the server. Does anyone have an idea for why it doesn’t always work? It seems more likely to work if I’m debugging the code, so I wonder if it has to do with timing?
This is an FMX application running on Windows and I’m using Delphi 10.4.
Note that I have changed the link to a fake one for posting here so obviously the code below will always return 0 if you try it.
uses IdHTTP, IdStack;

function CheckFileOnlineExists(const OnlineFile: string; var Size: Int64): Byte;
var
IdHttp: TIdHTTP;
begin
Result := 0; // File not found
IdHttp := TIdHTTP.Create(nil);
try
try
IdHttp.Head(OnlineFile);
Size := IdHttp.Response.ContentLength;
if Size > 0 then Result := 2; // File found
except
on E: EIdHTTPProtocolException do ;
on E: EIdSocketError do Result := 1; // No internet
end;
finally
IdHttp.Free;
end;
end;

procedure TMainForm.FormActivate(Sender: TObject);
Var
LSize : Int64;
LRes : Byte;
begin
// Check if online file exists
LRes := CheckFileOnlineExists(‘http://websiteurl.com/file_test.png’, LSize);
if (LRes <> 2) or (LSize <> 5497) then begin
if LRes = 0 then
Caption := ‘Website check file not found. This app will close’
else
Caption := ‘Internet connection is needed to run this application’;
Close;
end;
end;

Comments are closed.