获取远程文件大小

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

最近有些问题,因为它给出了一个无效的文件大小。

Putty显示:1,240,214字节(有效), vb.net的WebRequest显示:1,246,314字节(无效!)

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


想知道一下,网络请求是否可能在响应头中计算有效载荷的大小,而 Putty 则不会? - George Johnston
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相同的结果?


ContentLength 返回 1,246,314 字节,这意味着它与 WebRequest 一样是无效的大小。Putty 的 ls -l 给出了 1,240,214 字节,WinSCP 文件属性也给出了 1,240,214 字节的输出... - Lucas
你能否直接取两者的原始数据进行比较,而不是试图猜测它们之间的实际差异? - George Johnston
@GeorgeJohnston 没有猜测!一个文件之间可能有什么区别?没有。这只取决于本地 - Putty 和远程文件大小。所有从本地计算机对文件的请求都会给出有效的文件大小,而远程计算机则会给出虚假的文件大小。 - Lucas

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接