Lucas
Lucas

Reputation: 3715

Getting remote file size

What is the best way to get a remote file size in vb.net? Recently I was using this code:

        Dim Request As System.Net.WebRequest
        Dim Response As System.Net.WebResponse
        Dim FileSize As Integer
        Request = Net.WebRequest.Create("http://my-url.com/file.exe")
        Request.Method = Net.WebRequestMethods.Http.Get
        Response = Request.GetResponse
        FileSize = Response.ContentLength

From some time it doesn't work properly because it is giving a invalid file size.

Putty says: 1.240.214 bytes (valid), vb.net's WebRequest says: 1.246.314 bytes (invalid!)

It looks like WebRequest is using some kind of cache... Is there a better way to obtain remote file size?

Upvotes: 3

Views: 1648

Answers (2)

Ray E
Ray E

Reputation: 154

Try this:

Imports System.Net    
    
    Try
       Dim theSeekRequest As HttpWebRequest = CType(WebRequest.Create("https://www.somesite.co.za/filetocheck.txt"), HttpWebRequest)
       theSeekRequest.Timeout = 10000  ' 10 seconds
       Dim theSeekResponse As HttpWebResponse = CType(theSeekRequest.GetResponse(), HttpWebResponse)
       theSeekResponse = theSeekRequest.GetResponse
       Dim SitefileSize As Long = theSeekResponse.ContentLength
    Catch ex As Exception
       MsgBox("Remote request timed out.")
    End Try

Upvotes: 0

Karl Anderson
Karl Anderson

Reputation: 34846

How about you make a HEAD request, like this:

Dim req As System.Net.WebRequest = System.Net.HttpWebRequest.Create("http://my-url.com/file.exe")
req.Method = "HEAD"

Using resp As System.Net.WebResponse = req.GetResponse()
    Dim ContentLength As Integer

If Integer.TryParse(resp.Headers.[Get]("Content-Length"), ContentLength) Then
    ' Use ContentLength variable here 
    End If
End Using

Does that give you the same result as PuTTY?

Upvotes: 1

Related Questions