Der King Der King - 3 years ago 145
Vb.net Question

WebException - Blocking For Each Loop

I am learning to code since a few months.
Today I want to code a password manager. Everything works fine but the get icon function has problem if a host is unreachable. This function is to get the favicon from the webpage.

Try

For Each myItem As ListViewItem In lv_data.Items

Dim baseurl = myItem.Text
Dim url As Uri = New Uri(baseurl)

If url.HostNameType = UriHostNameType.Dns Then
Dim iconURL = "http://" & url.Host & "/favicon.ico"

Dim request As System.Net.WebRequest = System.Net.HttpWebRequest.Create(iconURL)
Dim response As System.Net.HttpWebResponse = request.GetResponse()
Dim stream As System.IO.Stream = response.GetResponseStream()
imglist.Images.Add(Image.FromStream(stream))
lv_data.Items.Item(myItem.Index).ImageIndex = myItem.Index
End If

Next
Catch ex As WebException

End Try


Some servers respond with a Exception :


Remote host could not be resolved


.
When that happens the whole for each loop stops. I am looking for a way to ignore that error and proceed with the next item from the listview.

Can anybody give me a tip or maybe a solution.

Best regards,
Der King

Answer Source

First move the try catch inside the loop

For Each myItem As ListViewItem In lv_data.Items
    Try

       Dim baseurl = myItem.Text
       Dim url As Uri = New Uri(baseurl)
       ...
    Catch
    End Try
Next

This will allow your code to continue inside the foreach loop when it encounters an exception in retrieving the favicon.ico

The next problem is how you address the images in the imagelist. When you encounter the exception because your code cannot retrieve the favicon you don't add anything to the ImageList.
At this point your ImageList and your ListView.Items don't contain the same number of elements, thus you cannot use the myItem.Index to reference the image in the ImageList.

But, because the image has been just added to the ImageList in the previous line, then you are certain that the image required is the last element of the ImageList. So you can use the ImageList.Images.Count property (less 1)

imglist.Images.Add(Image.FromStream(stream))
myItem.ImageIndex = imgList.Images.Count - 1

(Notice that you can use directly myItem in this context)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download