Reader Level:
ARTICLE

Simple web File download in VB.NET

Posted by Bill Farley Articles | Visual Basic .NET November 10, 2012
This is a simple program that shows how to download files from the web and save them.
  • 0
  • 0
  • 27636

Description:

This is a simple program that shows how to download files from the web and save them. The program uses the HttpWebRequest and HttpWebResponse classes to request and retrieve the requested file. The data are read into a buffer. A FileStream class is used to save the file to disk. In this example, a doppler radar map that covers the area I live is requested and saved to a file called "weather.jpg". Since the data are downloaded and read into the buffer asynchronously, a loop is required to read and keep track of how many bytes have been read, and the point in the stream where the next read should start. The loop will continue until the buffer is full or 0 bytes are read, indicating the end of the stream has been reached. The buffer must be sized large enough to hold the file. This is not a problem in this case as the doppler jpg's are a standard and known size.

Requirement:

Requires .NET SDK

How To Compile?

vbc /r:System.Net.dll /r:System.IO.dll webretrieve.vb.

Source Code

Imports System.IO
Imports System.Net
Imports System.Text
Class WebRetrieve
Public Shared Sub Main()
Dim wr As HttpWebRequest = CType(WebRequestFactory.Create("http://maps.weather.com/web/radar/us_orl_ultraradar_large_usen.jpg"), HttpWebRequest)
Dim ws As HttpWebResponse = CType(wr.GetResponse(), HttpWebResponse)
Dim str As Stream = ws.GetResponseStream()
Dim inBuf(100000) As Byte
Dim
bytesToRead As Integer = CInt(inBuf.Length)
Dim bytesRead As Integer = 0
While bytesToRead > 0
Dim n As Integer = str.Read(inBuf, bytesRead, bytesToRead)
If n = 0 Then
Exit
While
End
If
bytesRead += n
bytesToRead -= n
End While
Dim
fstr As New FileStream("weather.jpg", FileMode.OpenOrCreate, FileAccess.Write)
fstr.Write(inBuf, 0, bytesRead)
str.Close()
fstr.Close()
End Sub 'Main
End Class 'WebRetrievev

COMMENT USING

Trending up