我是c#的新手,我还在努力学习这一切。
从ftp下载文件时,我已经为进度条创建了这个代码,它实际上工作得很好。但进步价值是完全错误的。看起来它不知何故是字节值。但奇怪的是当我将值打印到屏幕上时,它会打印正确的值。
private void frm_movie_db_Load(object sender, EventArgs e)
{
if (!File.Exists("movies.list.gz"))
{
bg_worker.RunWorkerAsync();
}
}
private void bg_worker_DoWork(object sender, DoWorkEventArgs e)
{
string strDownloadFrom = "ftp://ftp.sunet.se/pub/tv+movies/imdb/movies.list.gz";
string strDownloadTo = "movies.list.gz";
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(strDownloadFrom);
request.Method = WebRequestMethods.Ftp.GetFileSize;
request.Credentials = new NetworkCredential("anonymous", "");
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = true;
Int64 intFileSize = request.GetResponse().ContentLength;
Int64 intRunningByteTotal = 0;
request = (FtpWebRequest)FtpWebRequest.Create(strDownloadFrom);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential("anonymous", "");
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream reader = response.GetResponseStream();
Stream writer = new FileStream(strDownloadTo, FileMode.Create, FileAccess.Write, FileShare.None);
byte[] byteBuffer = new byte[1024];
int intByteSize = 0;
int intProgressPct = 0;
while ((intByteSize = reader.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
{
if (intByteSize == 0)
{
intProgressPct = 100;
bg_worker.ReportProgress(intProgressPct);
}
else
{
writer.Write(byteBuffer, 0, intByteSize);
if (intByteSize + intRunningByteTotal <= intFileSize)
{
intRunningByteTotal += intByteSize;
double dIndex = intRunningByteTotal;
double dTotal = byteBuffer.Length;
double dProgressPct = (double)(dIndex / dTotal);
intProgressPct = (int)dProgressPct;
bg_worker.ReportProgress(intProgressPct);
}
}
}
//reader.Close();
//mem_stream.Close();
//response.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void bg_worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//pb_download_files.Value = e.ProgressPercentage;
lbl_progress_pct.Text = e.ProgressPercentage.ToString() + "%";
}
private void bg_worker_RunWorkerComplete(object sender, RunWorkerCompletedEventArgs e)
{
pnlProgress.Visible = false;
}
我希望有人可以帮助我,因为我已经做了所有事情来解决这个问题。
祝你好运 的Jesper
答案 0 :(得分:4)
你完全弄错了百分比进度计算:perc必须是 100 x current / total ,因此您使用了错误的值。
试试这个:
double dProgressPct = 100.0 * intRunningByteTotal / intFileSize;
bg_worker.ReportProgress((int)ProgressPct);
public void ReportProgress(int percentProgress)
其中 percentageProgress 是完成后台操作的百分比,从0到100。
答案 1 :(得分:1)
double dTotal = byteBuffer.Length;
不将总字节数分配给dTotal。 byteBuffer是一个常量为1024字节的缓冲区。尝试像
这样的东西double dTotal = reader.Length;
检索流的字节长度。
答案 2 :(得分:1)
double dTotal = byteBuffer.Length;
double dProgressPct = (double)(dIndex / dTotal);
我想你想要:
double dProgressPct = (double)(dIndex / intFileSize );