Downloading a file in Delphi

Viewed 31069

A google search shows a few examples on how to download a file in Delphi but most are buggy and half of the time don't work in my experience.

I'm looking for a simple robust solution which will let me download a single exe (for updating my app) and will hold the execution of the current update thread until the download is done or errors out. The process is already threaded so the download code should hold execution until it's done (hopefully).

Here's two implementations, both seem very complicated
1. http://www.scalabium.com/faq/dct0116.htm
2. http://delphi.about.com/od/internetintranet/a/get_file_net.htm

4 Answers

For people that has later version of delphi, you can use this:

var
  http : TNetHTTPClient;
  url : string;
  stream: TMemoryStream;
begin
  http := TNetHTTPClient.Create(nil);
  stream := TMemoryStream.Create;
  try
    url := YOUR_URL_TO_DOWNLOAD;
    http.Get(url, stream);
    stream.SaveToFile('D:\Temporary\1.zip');
  finally
    stream.Free;
    http.Free;
  end;
end;

Using URLMon.

errcode := URLMon.URLDownloadToFile(nil,
                      PChar('http://www.vbforums.com/showthread.php?345726-DELPHI-Download-Files'),
PChar( 'a:\download.htm'),
      0,
      nil);
if errcode > 0 then
      showmessage('Error while downloading: ' + inttostr(errcode));
Related