我是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;
}
我希望有人可以幫助我,因爲我已經做了所有的事情來解決這個問題。
問候 加斯帕
有與它們的類型前綴的變量名沒有價值。閱讀本文:http://stackoverflow.com/questions/111933/why-shouldnt-i-use-hungarian-notation – jeroenh
否,'lbl_progress_pct.Text = e.ProgressPercentage.ToString()+「%」;'不顯示正確的價值。 –
這個'double dProgressPct =(double)(dIndex/dTotal);'不是百分比的計算。 – Reniuz