Download File

jamie_pattison

Well-known member
Joined
Sep 9, 2008
Messages
116
Programming Experience
Beginner
I am using a HTTPWebRequest to check for a file. Originally if a file was found i took action i.e. sent an email. Now i would like it so if the file is found it downloads it.

After reading some threads im a little confused with the approach i should take.

1. Should i use a fileStream to download the file?
2. Some suggest Web Client, but i dont want to rewrite the entire application.
3. If using HttpWebRequest and FileStream to download is there a way to retry the download if the connection drops and continue from where it left off?

Thanks
 
1. FileStream class can't download a file, it is just a stream for reading/writing a local file.
2. WebClient class is just a simpler interface to the WebRequest classes. My.Computer.Network object is an even simpler one.
3. It depends, some servers support partial downloads. Research HttpWebRequest.AddRange method.
I am using a HTTPWebRequest to check for a file. Originally if a file was found i took action i.e. sent an email. Now i would like it so if the file is found it downloads it.
If you are going to download it if it exist, then just download it straight away and catch the exception if it don't. No need for duplicate requests. Catching network exceptions must be done in any case.
 
Yes.... that led me to the link Simple web File download in VB.NET and gave me the impression to use FileStream, although after your reply i then was under the impression im on the wrong lines?

My reason for asking if i should use FileStream was in case there was another way to do the same task.
 
Last edited:
As I said, you can use a FileStream to read/write a file, that by itself has nothing to do with downloading files from internet. Yes, you could use a FileStream to write the downloaded data to a file, and so would for example the File class do or other means of saving data to a file.
 
I now have the code but it doesnt seem to download the entire file, only a few bytes. If i change the buffer value it downloads according to it?

Dim str As Stream
Dim bBuff(80000) As Byte
Dim bytesToRead As Integer = CInt(bBuff.Length)
Dim readBytes As Integer = 0

Try
wrq = WebRequest.Create("http://localhost/test/file.zip")
wrq.Credentials = New NetworkCredential("username", "password")
wr = wrq.GetResponse
str = wr.GetResponseStream

While bytesToRead > 0
Dim i As Integer = str.Read(bBuff, 0, bytesToRead)
If i = 0 Then
Exit While
End If
readBytes += i
bytesToRead -= i
End While

fs = New FileStream(Path, FileMode.Create, FileAccess.Write)
fs.Write(bBuff, 0, readBytes)

' Clean up code to flush and close

Thanks
 
Last edited:
Back
Top