上传、下载文件如何获取传输速度
C#使用System.Net.WebRequest、System.Net.HttpWebRequest、System.Net.FileWebRequest这几个类传输文件,如何获取传输速度,即每秒传输多少kb --------------------编程问答-------------------- 1、获取文件的大小将文件内容转换为字符串,取length即可
(file.length)
2、获取传输时间
传输前后分别获取时间:
DateTime.Now.Ticks;
相减即可 --------------------编程问答-------------------- 类似这样来做,以前做过一个下载工具软件,具体代码参考 FileDownLoader1.0 主要代码
--------------------编程问答--------------------
Using sw As New IO.FileStream(strSavePath, IO.FileMode.Create)
Dim nRead As Integer = 0
Dim speedtimer As New Stopwatch
Dim currentspeed As Double = -1
Dim readings As Integer = 0
Do
If Bgw.CancellationPending Then
Exit Do
End If
speedtimer.Start()
Dim readBytes(4095) As Byte
Dim bytesread As Integer = theResponse.GetResponseStream.Read(readBytes, 0, 4096)
nRead += bytesread
Dim percent As Short = (nRead * 100) / length
Me.Invoke(safedelegate, length, nRead, percent, currentspeed)
If bytesread = 0 Then Exit Do
sw.Write(readBytes, 0, bytesread)
speedtimer.Stop()
readings += 1
If readings >= 5 Then
currentspeed = 20480 / (speedtimer.ElapsedMilliseconds / 1000)
speedtimer.Reset()
readings = 0
End If
Loop
theResponse.GetResponseStream.Close()
sw.Close()
End Using
你这个不能作为实时的下载速度,只是下载完成之后获取的,速度不准确 --------------------编程问答-------------------- 传输的速度通知都是取决于接收方的才能准确!
像ftp之类的文件传输协议,都是发送一块,接收端接收后通知发送端,这样发送端才能知道准确的发送进度。
基于web的由于http的无连接特点,接收端没办法通知客户端接收的情况,所以需要能够对接收端进行改造。
改造步骤:
1、Web接收文件的时候,记录接收进度到Session中,并且暴露一个url形式或者其它形式的接口来获取进度信息
2、发送端定时去调用进度信息的接口得到准确的进度。
许多web的带进度条的实现都是这样的。除了用flash或者sl之类的富客户端技术。
如果是winform程序,为什么要用webclient的方式上传的?没整明白
补充:.NET技术 , C#