VB.net 檔案下載示例
Imports System.IO
Imports System.Net
Public Class Form1
Private Sub btnDown_Click(sender As Object, e As EventArgs) Handles btnDown.Click
Dim hwq As HttpWebRequest
Dim hwp As HttpWebResponse
Dim colHeader As WebHeaderCollection '響應頭資訊集合
Dim lngSize As Int64 '要下載檔案的總大小
Dim lngCurSize As Int64 '已經下載大小
Dim lngNet As Int64 '計算網速用
Dim stRespones As Stream '響應流
Dim st As FileStream '本地流
Dim intCurSize As Int64
Dim bytBuffer(512) As Byte '快取大小
Dim datLast As DateTime '最後一次時間
Dim intDiff As Int32 '兩次時間差(秒)
datLast = Now '取得開始時間
hwq = CType(HttpWebRequest.Create(txtAddress.Text), HttpWebRequest) '請求物件建立
hwp = hwq.GetResponse '取得響應物件
colHeader = hwp.Headers '取得響應頭
lngSize = colHeader.Get("Content-Length") '取得要下載檔案的大小
stRespones = hwp.GetResponseStream '取得響應流
st = New FileStream("D:\2.zip", FileMode.Create) '本地儲存檔案
intCurSize = stRespones.Read(bytBuffer, 0, bytBuffer.Length) '響應流中讀取
Do While (intCurSize > 0) '只要有資料就繼續
st.Write(bytBuffer, 0, intCurSize) '寫入本地檔案
intDiff = DateDiff(DateInterval.Second, datLast, Now)
lngCurSize = lngCurSize + intCurSize
lngNet = lngNet + intCurSize '單位時間內的下載量
If intDiff >= 1 Then
txtState.Text = "檔案大小:" & lngSize & vbCrLf &
"已經下載:" & lngCurSize & vbCrLf &
"下載速度:" & CInt(lngNet / intDiff / 1024) & "k/s" & vbCrLf &
"下載百分比:" & Math.Round(lngCurSize/lngSize*100, 2) & " %"
datLast = Now
lngNet = 0
End If
Application.DoEvents()
intCurSize = stRespones.Read(bytBuffer, 0, bytBuffer.Length) '繼續讀取
Loop
txtState.Text = "下載完成!"
st.Close()
stRespones.Close()
End Sub
End Class