Home > Back-end >  How to calculate the file download size amount already downloaded out of the total size?
How to calculate the file download size amount already downloaded out of the total size?

Time:11-24

private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e, Stopwatch sw)
{
    string downloadProgress = e.ProgressPercentage   "%";
    string downloadSpeed = string.Format("{0} MB/s", (e.BytesReceived / 1024.0 / 1024.0 / sw.Elapsed.TotalSeconds).ToString("0.00"));
    string downloadedMBs = Math.Round(e.BytesReceived / 1024.0 / 1024.0)   " MB";
    string totalMBs = Math.Round(e.TotalBytesToReceive / 1024.0 / 1024.0)   " MB";
    
    string progress = $"{downloadedMBs}/{totalMBs} ({downloadProgress}) @ {downloadSpeed}"; // 10 MB / 100 MB (10%) @ 1.23 MB/s
    lblDownloadProgress.Text = progress;
    textProgressBar1.Value = e.ProgressPercentage;
    textProgressBar1.CustomText = progress;
} 

I can see with a break point that the variable value of e.BytesReceived and e.TotalBytesToReceive are changing but on the progress variable the downloadedMBs and totalMBs values are 0 all the time.

Edit:
Example for values that cause the problem:
e.BytesReceived: 2196
e.TotalBytesToReceive: 194899

CodePudding user response:

The values you reported for both e.TotalBytesToReceive (194899) and e.BytesReceived (2196) are less than a half of 1024.0*1024.0==1048576.0.

Therefore when you divide them twice by 1024.0
(equivalent to dividing by 1024.0*1024.0==1048576.0) you get a value less than 0.5, and when rounded using Math.Round will give 0.

You can either keep all the calculations in doubles, or specify the number of digits after the decimal point you are interested in, as a second argument to Math.Round.
See in the documentation.

For example if you are interested in 3 digits after the decimal point, you can use:

long bytesReceived = 2196;
long totalBytesToReceive = 194899;

//------------------------------------------------------------------V--------------------
string downloadedMBs = Math.Round(bytesReceived / 1024.0 / 1024.0,  3).ToString()   " MB";
string totalMBs = Math.Round(totalBytesToReceive / 1024.0 / 1024.0, 3).ToString()   " MB";

Console.WriteLine("downloadedMBs: "   downloadedMBs);
Console.WriteLine("totalMBs: "   totalMBs);

Output:

downloadedMBs: 0.002 MB
totalMBs: 0.186 MB
  • Related