Getting no error messages using Net.WebClient on a valid but empty path

jbl_ks

Member
Joined
Dec 16, 2010
Messages
24
Programming Experience
Beginner
Bing Satellite map tiles at zoom level 19 and above are not available for some areas while available in others. If I send a valid URL for a tile that I want to download but is not available, in a browser window the server will return an error message. Using the sub below I see nothing when this happens I just create a file with the correct name and it is empty, size = 0. The loop might get 50-75 empty files.
If my Try/Catch block is OK, then I need some method of checking the first files length or contents to see if it is empty before exiting the Sub. That also might slow it down enough to where the Sleep(50) wouldn't be necessary.

VB.NET:
Public Sub DownloadBingImages(ByVal strURL As String, ByVal intColumn As String, ByVal intRow As String)
    Dim strImageName As String = "MyNew.jpg"
    Dim strImagePath As String = Path.Combine(Form1.strImageFolder, strImageName)
    Dim webClient As New WebClient
    Dim uri As Uri = New Uri(strURL)
    If (Not Directory.Exists(strImageFolder)) Then
        Directory.CreateDirectory(strImageFolder)
    End If
    Try
        webClient.Headers.Add(Net.HttpRequestHeader.UserAgent, ".Net client")
        webClient.DownloadFileAsync(uri, strImagePath)
        
        ' If this image is not available I get no error messages
        
    Catch ex As HttpListenerException
        MessageBox.Show("Error accessing " & strURL & " - " & ex.Message & " ", "Problem Getting File")
        
    Catch ex As Exception
        MessageBox.Show("Error accessing " & strURL & " - " & ex.Message & " ", "Problem Saving File")
        
    End Try

    Sleep(50) ' 1/20 second, don't hammer the server, will not work without this
End Sub
 
Instead of calling DownloadFileAsync, call DownloadDataAsync. That way you get the data in memory instead of straight to a file. You can test whether there is any data first and then save the file yourself if there is.

Also, with regards to slowing things down, you might want to consider two options:

1. Get all your URLs into an array or collection, start a new thread and then download the tiles in serial, i.e. one by one, in a loop. In that case you'd use a synchronous method rather than an asynchronous one.

2. Use the ThreadPool to queue up all the downloads. Call the SetMaxThreads method to limit the number of requests that can be serviced simultaneously.
 
Back
Top