Downloading Web Pages in VB.NET

In this article, you'll see VB.NET version of how to use Web classes to download a file through HTTP. You can use three different ways to download a file contents through HTTP.
  • 26365

In this article, you'll see VB.NET version of how to use Web classes to download a file through HTTP.

You can use three different ways to download a file contents through HTTP.

Using WebClient Class

The WebClient provides three different methods to download data either from the Internet, intranet, or local file system.

WebClient constructor doesn't take any arguments. In the following code, URL is the file name you want to download such as http://www.c-sharpcorner.com/default.asp. You can download any type of files using these methods such as image files, html and so on.

The following code downloads the entire file and displays its contents on the console.

Source Code:

Imports System
Imports System.IO
Imports System.Net
Module Module1
Sub Main()
'Address of URL
Dim URL As String = http://www.c-sharpcorner.com/default.asp
' Get HTML data
Dim client As WebClient = New WebClient()
Dim data As Stream = client.OpenRead(URL)
Dim reader As StreamReader = New StreamReader(data)
Dim str As String = ""
str = reader.ReadLine()
Do While str.Length > 0
Console.WriteLine(str)
str = reader.ReadLine()
Loop
End
Sub
End
Module

Using WebRequest Class

The WebRequest is an abstract base class. So you actually don't use it directly. You use it through it derived classes - HttpWebRequest and FileWebRequest.

You use Create method of WebRequest to create an instance of WebRequest. GetResponseStream returns data stream. The following sample example downloads data stream from a web page. 

Sample Code

Imports System
Imports System.IO
Imports System.Net
Module Module1
Sub Main()
'Address of URL
Dim URL As String = http://www.c-sharpcorner.com/default.asp
Dim request As WebRequest = WebRequest.Create(URL)
Dim response As WebResponse = request.GetResponse()
Dim reader As StreamReader = New StreamReader(response.GetResponseStream())Dim str As String = reader.ReadLine()
o While str.Length > 0
Console.WriteLine(str)
str = reader.ReadLine()
Loop
End Sub
End
Module

HttpWebRequest and HttpWebResponse classes works in same way too. Here is one sample example.

Using HttpWebRequest Class

Imports System
Imports System.IO
Imports System.Net
Module Module1
Sub Main()
'Address of URL
Dim URL As String = http://www.c-sharpcorner.com/default.asp
Dim request As HttpWebRequest = WebRequest.Create(URL)
Dim response As HttpWebResponse = request.GetResponse()
Dim reader As StreamReader = New StreamReader(response.GetResponseStream())
Dim
str As String = reader.ReadLine()
Do While str.Length > 0
Console.WriteLine(str)
str = reader.ReadLine()
Loop
End
Sub
End
Module

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.