views:

175

answers:

2

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

+6  A: 

The second approach is the standard way of using Internet resources using WinINet, a part of Windows API. I have used it a lot, and it has always worked well. The first approach I have never tried. (Neither is "very complicated". There will always be a few additional steps when using the Windows API.)

If you want a very simple method, you could simply call UrlMon.URLDownloadToFile. You will not get any fine control (at all!) about the download, but it is very simple.

Example:

URLDownloadToFile(nil,
                  'http://www.rejbrand.se',
                  PChar(ExtractFilePath(Application.ExeName) + 'download.htm'),
                  0,
                  nil);
Andreas Rejbrand
Hint: replace `Application.ExeName` with `ParamStr(0)` to remove the dependency on the `Forms` unit.
mjustin
@mjustin: True. But in production code, you will not want to save files to the application's directory anyway, which is read-only (Program Files), unless the program is portable (runs on a USB stick for example).
Andreas Rejbrand
Thanks for the answer Andreas. I went with the second approach which I posted since you said it was the standard, hopefully it turns out to be reliable. Thanks for your effort.
Daisetsu
+3  A: 

Why not make use of indy. If you use the TIdHTTP its simple

procedure DownloadFile;    
var
  IdHTTP1: TIdHTTP;
  Stream: TMemoryStream;
  Url, FileName: String;
begin    
  Url := 'http://www.rejbrand.se';
  Filename := 'download.htm';

  IdHTTP1 := TIdHTTP.Create(Self);
  Stream := TMemoryStream.Create;
  try
    IdHTTP1.Get(Url, Stream);
    Stream.SaveToFile(FileName);
  finally
    Stream.Free;
    IdHTTP1.Free;
  end;
end;

You can even add a progress bar by using the OnWork and OnWorkBegin Events

procedure IdHTTPWorkBegin(ASender: TObject; AWorkMode: TWorkMode;AWorkCountMax: Int64);
begin
  ProgressBar.Max := AWorkCountMax;
  ProgressBar.Position := 0;
end;

procedure IdHTTPWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
begin
  ProgressBar.Position := AWorkCount;
end;

I'm not sure if these event fire in the context of the main thread, so any updates done to VCL components may have to be done using the tidnotify component to aviod threading issues. Maybe someone else can check that.

MikeT