VB.NET: How to Check If an Image is Exist on Web

This time, I want to talk about images on the internet. More specifically about how to check whether the image exists or not via a web url. Using VB.NET code of course.

We need to declare this function in our project/form:
Private Declare Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" _
 (ByVal pCaller As LongByVal szURL As StringByVal szFileName As String, _
  ByVal dwReserved As LongByVal lpfnCB As LongAs Long

I got this code from this link. I've tried it myself, and It works.
http://www.vbforums.com/showthread.php?544655-RESOLVED-Check-to-see-if-a-image-exists-on-the-web

The original code is made for VB6, surprisingly this is also work in VB.NET. 
Here are the steps to impement it. First I made this UI on Form1.


And we could simply write these code:
Public Class Form1
  Private Declare Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" _
          (ByVal pCaller As LongByVal szURL As StringByVal szFileName As String, _
           ByVal dwReserved As LongByVal lpfnCB As LongAs Long
  Private Sub Button1_Click(sender As Object, e As EventArgsHandles Button1.Click
      Dim sURL As String = TextBox1.Text
      Dim As Long
      i = URLDownloadToFile(0, sURL, "", 0, 0)
      If i <> 0 Then
          MsgBox("File does not exist")
      Else
          MsgBox("File exists")
      End If
  End Sub
End Class

Then try to run the program. Input a valid image url into the textbox then click button1. The result will be as below.


Otherwise if url is not valid, it will give a message as below.








Post a Comment

0 Comments