我做了一些研究,以下可能是获取下载大小(以字节为单位)最简单和“最干净”的方法:
Public Function GetDownloadSize(ByVal URL As String) As Long
Dim r As Net.WebRequest = Net.WebRequest.Create(URL)
r.Method = Net.WebRequestMethods.Http.Head
Using rsp = r.GetResponse()
Return rsp.ContentLength
End Using
End Function
感谢Reed Kimble的建议,在我的初始MSDN问题中告诉我要处理WebResponse
。
上述代码将读取文件的响应头,而不是读取其正文。这意味着文件无需下载即可检查其大小。
这就是为什么有些代码需要首先下载文件;它们读取文件的正文而不是其头部。
希望这可以帮助您!
使用 WebClient ResponseHeaders
:
Public Shared Function GetFileSize(url As String) As Long
Using obj As New WebClient()
Using s As Stream = obj.OpenRead(url)
Return Long.Parse(obj.ResponseHeaders("Content-Length").ToString())
End Using
End Using
End Function
Dim DownloadSize As Long
Private Sub CheckDownloadSize(ByVal URL As String)
WebClient.DownloadFile(URL, IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.Temp, "tempdownload.tmp"))
End Sub
Private WithEvents WebClient As New WebClient
Private Sub WebClient_DownloadProgressChanged(ByVal sender As Object, ByVal e As System.Net.DownloadProgressChangedEventArgs) Handles WebClient.DownloadProgressChanged
DownloadSize = e.TotalBytesToReceive
WebClient.CancelAsync()
End Sub
.CancelAsync()
这一行即可。