I will provide a very simple program that will teach your how to download files from the website and save them. It uses to classes the first one is HttpWebRequest and the second one is HttpWebRequest to request and retrieve the requested file. The data is read into a buffer. In order to save the file on the disk the FileStream class is used. We will take an example of a image file. Like image.png. Normally a loop is required to read and keep the track how many bytes have been read to download and read the file. Till the time buffer is not 0 bytes the loop will continue till the end of stream. The size of buffer must be enough large to hold the data. The source code for it is as follows.
Code:
Imports System.IO
Imports System.Net
Imports System.Text
Class WebRetrieve
Public Shared Sub Main()
Dim wr As HttpWebRequest = CType(WebRequestFactory.Create("http://www.samplewebsite.com/image.png"), 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("image.png", FileMode.OpenOrCreate, FileAccess.Write)
fstr.Write(inBuf, 0, bytesRead)
str.Close()
fstr.Close()
End Sub 'Main
End Class 'WebRetrieve
Bookmarks