Delphi Programming with WinInet
InternetOpenURL and InternetReadFile Example
Using WinInet to download a file using HTTP
function DownloadFile( const url: string; const destinationFileName: string): boolean; var hInet: HINTERNET; hFile: HINTERNET; localFile: File; buffer: array[1..1024] of byte; bytesRead: DWORD; begin result := False; hInet := InternetOpen(PChar(application.title), INTERNET_OPEN_TYPE_PRECONFIG,nil,nil,0); hFile := InternetOpenURL(hInet,PChar(url),nil,0,0,0); if Assigned(hFile) then begin AssignFile(localFile,destinationFileName); Rewrite(localFile,1); repeat InternetReadFile(hFile,@buffer,SizeOf(buffer),bytesRead); BlockWrite(localFile,buffer,bytesRead); until bytesRead = 0; CloseFile(localFile); result := true; InternetCloseHandle(hFile); end; InternetCloseHandle(hInet); end;
Then to use this function:
if DownloadFile( 'http://www.cryer.co.uk/index.htm', 'c:\temp\index.htm') then ShowMessage('Success') else ShowMessage('Failed to download file');
- If you want to make use of this function in your application, then be aware that InternetOpen need only be called once in your application. The call to InternetOpen is only included in the above to give a self contained example.
- Whilst this example uses http to download an html file, it could also be used to download a zip, pdf or any other file that is accessible from the website.
- Whilst the heading given is "Using WinInet to download a file using HTTP", the above can be used for protocols other than HTTP.
These notes are believed to be correct for Delphi 6 and Delphi 7 and may apply to other versions as well.
About the author: Brian Cryer is a dedicated software developer and webmaster. For his day job he develops websites and desktop applications as well as providing IT services. He moonlights as a technical author and consultant.