How can I calculate the speed per sec, and the time left in sec? I've tried to use:
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {
long prevSum = 0;
while (fileTransfer.busy) {
rate = (fileTransfer.sum - prevSum);
RateLabel(rate); //converting prevSum to (int)KB/SEC
if (rate != 0)
left = (fileTransfer.fileSize - fileTransfer.sum) / rate;
TimeSpan t = TimeSpan.FromSeconds(left);
timeLeftLabel(FormatRemainingText(rate, t)); //show how much left
prevSum = fileTransfer.sum;
Thread.Sleep(1000);
}
}
but the rate and the time left goes up and down like (30MB/sec then 5MB/sec) permanently.
This is the sendfile code:
public static void sendFile(string filePath) {
// run the progres Form
Thread thFP = new Thread(fpRUN);
fileProgress fP = new fileProgress("Sending...");
thFP.Start(fP);
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
string fileName = Path.GetFileName(filePath);
byte[] fileData;
try {
//sending file name and file size to the server
busy = true;
fileSize = fs.Length;
byte[] fileDetial = null;
string detail = fileName + "," + fileSize.ToString();
fileDetial = Encoding.ASCII.GetBytes(detail);
client.Send(fileDetial);
//sending file data to the server
fileData = new byte[packetSize];
count = 0;
sum = 0;
fP.SizeLabel(fileSize); // tell the form the file size
while (sum < fileSize) {
fs.Seek(sum, SeekOrigin.Begin);
fs.Read(fileData, 0, fileData.Length);
count = client.Send(fileData, 0, fileData.Length, SocketFlags.None);
sum += count;
fP.ProgressBarFileHandler(sum,fileSize); //progressbar value
fP.SentLabel(sum); //tell the form how much sent
}
}
finally {
busy = false;
fs.Close();
fileData = null;
MessageBox.Show(string.Format("{0} sent successfully", fileName));
}
}
How can I fix that? Is there a better way to calculate the speed?
in form constructor
or add it from toolbox and set the previous values
the sum of sent bytes should be public so our method can get its value every second