3

在 vb.net 中获取远程文件大小的最佳方法是什么?最近我正在使用这段代码:

        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

有时它无法正常工作,因为它提供了无效的文件大小。

腻子说:1.240.214 字节(有效),vb.netWebRequest说:1.246.314 字节(无效!)

看起来 WebRequest 正在使用某种缓存......有没有更好的方法来获取远程文件大小?

4

2 回答 2

1

您如何提出 HEAD 请求,如下所示:

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

这会给您带来与 PuTTY 相同的结果吗?

于 2013-08-12T19:39:32.890 回答
0

尝试这个:

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
于 2022-02-27T07:08:00.133 回答