I am using urldownloadtofile() to download a file from the web to a local machine. The coding works fine in a Word macro but does not work in vb.net. The strange thing is that it used to work and as far as I know I have not changed any of the settings. I now get
AccessVioationException was unhandled (attempted to read or write protected memory) on the line DownloadFile2 = URLDownloadToFile(0&, _ .....
The coding is:
Option Explicit On
Public Class Form1
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 Declare Function DeleteUrlCacheEntry Lib "Wininet.dll" _
Alias "DeleteUrlCacheEntryA" _
(ByVal lpszUrlName As String) As Long
Private Const ERROR_SUCCESS As Long = 0
Private Const BINDF_GETNEWESTVERSION As Long = &H10
Private Const INTERNET_FLAG_RELOAD As Long = &H80000000
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' DownloadFromWeb Macro
' Macro created 3/16/2007 by Brian O'Gorman
Dim sSourceUrl As String
Dim sLocalFile As String
sSourceUrl = "http://18.104.22.168/TestText.csv
sLocalFile = "c:\Web Design\LIFEnet\TestText.cs
'Label1.Caption = sSourceUrl
'Label2.Caption = sLocalFile
'Attempt to delete any cached version of
'the file. Since we're only interested in
'nuking the file, the routine is called as
'a sub. If the return value is requires
'(calling as a function), DeleteUrlCacheEntry
'returns 1 if successful, or 0 otherwise, e.g.
' If DeleteUrlCacheEntry(source
Url) = 1 Then
' Debug.Print "cached file found and deleted"
' Debug.Print "no cached file for " & sourceUrl
' End If
'Note that the remote URL is passed as this is the
'name the cached file is known by. This does NOT
'delete the file from the remote server.
If DownloadFile2(sSourceUrl, sLocalFile) = True Then
Private Function DownloadFile2(ByVal sSourceUrl As String, _
ByVal 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.
DownloadFile2 = URLDownloadToFile(0&, _
0&) = ERROR_SUCCESS
Would be grateful for help on this.