| 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. The downloaded file can then be either opened and displayed in VB (as the illustration shows for a html file), or the path and filename can be passed to ShellExecute or ShellExecuteEx for opening in the associated application. For multiple files It downloads them one at a time, and the wrapper returns true if the download of each file was successful. The pCaller member of the API is used to specify the address of the controlling IUnknown interface when the call is used in an ActiveX controls. For use in an application, 0& (null) is passed. This code is loosely based on a msnews newsgroup posting by Matthew Gates. BAS Module Code None. -------------------------------------------------------------------------------- Form Code Drop a command button (Command1) and a text box (Text1) onto a form and set the Multiline property to True. Add the following code and change the remote URL to a valid file on a server, and the local file name to valid a valid folder on your system: -------------------------------------------------------------------------------- Option Explicit 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 Sub Form_Load() Command1.Caption = "Download File" End Sub Private Sub Command1_Click() Dim sourceUrl As String Dim targetFile As String Dim hfile As Long sourceUrl = "http://www.mvps.org/vbnet/faq/main/fileloadtext.htm" targetFile = "c:\deleteme.htm" Label1.Caption = sourceUrl Label2.Caption = targetFile If DownloadFile(sourceUrl, targetFile) Then hfile = FreeFile Open targetFile For Input As #hfile Text1.Text = Input$(LOF(hfile), hfile) Close #hfile End If End Sub Public Function DownloadFile(ByVal sURL As String, _ ByVal sLocalFile As String) As Boolean Dim lngRetVal As Long 'if the API returns ERROR_SUCCESS (0), 'return True from the function DownloadFile = URLDownloadToFile(0&, _ sURL, _ sLocalFile, _ 0&, _ 0&) = ERROR_SUCCESS End Function |
Downloading Files using URLDownloadToFile |
Express News India | Freelance ecommerce web development India