Ensure that a valid URL exist and download the data from a text file hosted on the server from VB.net

Posted by Rajnilari2015 under VB.NET category on | Points: 40 | Views : 371
The below code will do so

Imports System.Net

Namespace ConsoleApplication1
Class Program
Private Shared Sub Main(args As String())
Dim fileLocation As String = "http://xyz.net/sample.txt"
Dim serverResponse = GetServerResponse(fileLocation)
Console.WriteLine("URL Validity : {0} " & vbLf & " Server Response : {1}", serverResponse.Item1, serverResponse.Item2)
End Sub

Private Shared Function GetServerResponse(fileLocation As String) As Tuple(Of Boolean, String)
Dim isValidURL As Boolean = True
Dim data As String = String.Empty
Using client As New WebClient()
data = client.DownloadString(fileLocation)
Catch weX As WebException
isValidURL = Not isValidURL
data = weX.Message
End Try
End Using
Return Tuple.Create(Of Boolean, String)(isValidURL, data)
End Function
End Class
End Namespace

We are using the WebClient class for this purpose that resides under System.Net .The WebClient class Provides common methods for sending data to and receiving data from a resource identified by a URI.This program checks if a file Exists at a specified URI and if so, returns the file content.If the URL is correct and the file exists at the proper URL,it will return isValidURL True.If the URL is wrong or the file does not exist,it will return isValidURL false. If the URL is wrong or the file does not exist, that it will hit the catch block and the respective error response will be return back.

Comments or Responses

Login to post response