我正在做一个简单的程序,下载一堆文件。现在我想显示用户“xx剩余时间”(就像你看到的uTorrent一样)。FTP下载估计剩余时间
到目前为止,这是我得到
下载文件
// Download the file
//Console.WriteLine("Downloading \"{0}\" from {1}...", node.Name, Config.FTP_HOST + "/" + node.DirectoryFileIsIn);
FtpWebRequest request = CreateRequest("ftp://" + Config.FTP_HOST + "/" + node.DirectoryFileIsIn + "/" + node.Name, WebRequestMethods.Ftp.DownloadFile.ToString());
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
FileStream filestream = new FileStream(new_path, FileMode.Create);
int chunkSize = 1024;
long total = node.FileSize;
int streamPosition = 0;
while (true)
{
byte[] buffer = new byte[Math.Min(chunkSize, node.FileSize - streamPosition)];
//byte[] buffer = new byte[chunkSize];
int readBytes = responseStream.Read(buffer, 0, buffer.Length);
if (readBytes == 0)
break;
currentFileSizeDownloaded += readBytes; // total bytes downloaded
bytesSnapshot += readBytes; // for tracking download speed
streamPosition += readBytes; // for tracking response stream position
filestream.Write(buffer, 0, readBytes);
}
filestream.Flush();
//Console.WriteLine("Download Complete, status {0}", response.StatusDescription);
response.Dispose();
filestream.Dispose();
response.Close();
filestream.Close();
捕获字节下载(单独的线程)
// Calculate total download time
public static void CalculateDownloadTime()
{
bytesSnapshot = 0;
int waitTime = 10000;
Thread.Sleep(waitTime); // sleep 10 seconds
if (bytesSnapshot > 0)
{
double downloadSpeed = (bytesSnapshot/10); // bytes per second
long remainingTime = (totalFileSizeToDownload - currentFileSizeDownloaded)/(long)downloadSpeed;
Console.WriteLine("Download speed {0}", Formatting.FormatBytes((long)downloadSpeed));
Console.WriteLine("Remaining time {0}", Formatting.FormatSeconds(remainingTime));
Console.WriteLine();
}
else
{
Console.WriteLine("byteSnapshot = 0"); // DEBUG
downloadTracker.Abort();
return;
}
CalculateDownloadTime();
}
输出
Download speed 106,73 KB
Remaining time 0:01:52
Download speed 9,02 KB
Remaining time 0:22:05
Download speed 8,94 KB
Remaining time 0:22:06
Download speed 7,68 KB
Remaining time 0:25:35
Download speed 7,68 KB
Remaining time 0:25:25
Download speed 8,12 KB
Remaining time 0:23:52
Download speed 8,39 KB
Remaining time 0:22:56
Download speed 169,65 KB
Remaining time 0:00:58
Download speed 591,03 KB
Remaining time 0:00:06
Download speed 393,86 KB
Remaining time 0:00:00
byteSnapshot = 0
正如你可以看到我做错了..下载速度does not看起来现实给我的时间是路要走,但我无法弄清楚是怎么回事错..
我认为我的问题在于计算下载速度,所以如果下载速度是正确的,时间将是固定的...