Download File - VB6

If you want to do it with code only (no Internet Transfer Control), VBNet.mvps.org has a really good how-to article that uses the URLDownloadToFile API call.

From the article:

The URLDownloadToFile API is available on all versions of the Windows operating system (except Win3, WinNT3.x). By passing the remote file name and the local file path and name, the API downloads the bits of the specified file saving them as the target name. The function works with all file types - plain text, images, html, mpg, wav and zip files etc. without modification to the routine or concern for the file being downloaded, nor is there any apparent size restriction or limitation.

Private Declare Function URLDownloadToFile Lib "urlmon" _
   Alias "URLDownloadToFileA" _
  (ByVal pCaller As Long, _
   ByVal szURL As String, _
   ByVal szFileName As String, _
   ByVal dwReserved As Long, _
   ByVal lpfnCB As Long) As Long

Private Const ERROR_SUCCESS As Long = 0
Private Const BINDF_GETNEWESTVERSION As Long = &H10
Private Const INTERNET_FLAG_RELOAD As Long = &H80000000

Public Function DownloadFile(sSourceUrl As String, _
                             sLocalFile As String) As Boolean

  //'Download the file. BINDF_GETNEWESTVERSION forces 
  //'the API to download from the specified source. 
  //'Passing 0& as dwReserved causes the locally-cached 
  //'copy to be downloaded, if available. If the API 
  //'returns ERROR_SUCCESS (0), DownloadFile returns True.
   DownloadFile = URLDownloadToFile(0&, _
                                    sSourceUrl, _
                                    sLocalFile, _
                                    BINDF_GETNEWESTVERSION, _
                                    0&) = ERROR_SUCCESS

End Function

FYI - in testing on Windows 7, it would only return the cached version, so I had to use the extra function mentioned in the article to clear it first (and that worked).

Private Declare Function DeleteUrlCacheEntry Lib "Wininet.dll" _
   Alias "DeleteUrlCacheEntryA" _
  (ByVal lpszUrlName As String) As Long

Then just call the above function with the destination URL first, to clear the cache.


You don't need API calls, you don't need the Internet Transfer control. Just do it the easy way, using native VB6 code. Here's an excellent article by Karl Peterson with sample code.


Try this

Sub DownloadFile(url, path)

   Dim objReq
   Dim objStream

   Set objReq = CreateObject("MSXML2.XMLHTTP")
   objReq.Open "GET", url, False
   objReq.send

   If objReq.Status = 200 Then
       Set objStream = CreateObject("ADODB.Stream")
       objStream.Open
       objStream.Type = 1

       objStream.Write objReq.ResponseBody
       objStream.Position = 0

       objStream.SaveToFile path, 2
       objStream.Close
       Set objStream = Nothing
   End If

   Set objReq = Nothing

End Sub

Tags:

Download

Vb6