【发布时间】:2015-10-08 17:02:45
【问题描述】:
所以我尝试使用进度条来直观地显示通过 ftp 上传文件的进度。 我似乎无法弄清楚为什么进度条和其他 3 个标签(labelSpeed、labelPerc、labelUploaded)不起作用。
任何帮助将不胜感激。谢谢。
PS:我附上了我的代码片段供查看。
Stopwatch sw = new Stopwatch(); //<-- The stopwatch which we will be using to calculate the upload speed
public void Upload(string ftpServer, string username, string password, string filename, string folder1, string folder2, string folder3)//<-- Uploads image to ftp directory
{
string ftpfolderpath = folder1 + "/" + folder2 + "/" + folder3;
MakeFTPDir(ftpServer, ftpfolderpath, username, password); //<-- Makes the new directory, if there isnt one already
using (WebClient client = new WebClient())
{
client.UploadFileCompleted += new UploadFileCompletedEventHandler(Completed); //<--NEW
client.UploadProgressChanged += new UploadProgressChangedEventHandler(ProgressChanged); //<--NEW
sw.Start(); //<-- Start the stopwatch which we will be using to calculate the upload speed
client.Credentials = new NetworkCredential(username, password);
client.UploadFile(ftpServer + "/" + folder1 + "/" + folder2 + "/" + folder3 + "/" + new FileInfo(filename).Name, "STOR", filename); //<-- uploads image to ftp Directory
}
}
private void ProgressChanged(object sender, UploadProgressChangedEventArgs e) //<-- The event that will fire whenever the progress of the WebClient is changed
{
// Calculate upload speed and output it to labelSpeed.
labelSpeed.Text = string.Format("{0} kb/s", (e.BytesSent / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00"));
// Update the progressbar percentage only when the value is not the same.
progressBar1.Value = e.ProgressPercentage;
// Show the percentage on our label.
labelPerc.Text = e.ProgressPercentage.ToString() + "%";
// Update the label with how much data have been uploaded so far and the total size of the file we are currently uploading
labelUploaded.Text = string.Format("{0} MB's / {1} MB's",
(e.BytesSent / 1024d / 1024d).ToString("0.00"),
(e.TotalBytesToSend / 1024d / 1024d).ToString("0.00"));
}
private void Completed(object sender, UploadFileCompletedEventArgs e) //<-- The event that will trigger when the WebClient is completed
{
if (e.Error != null)
{
string error = e.Error.ToString(); // error = "Custom error message here";
MessageBox.Show(error);
return;
}
sw.Reset(); // Reset the stopwatch.
if (e.Cancelled == true)
{
MessageBox.Show("Image Upload has been canceled.");
}
else
{
MessageBox.Show("Image Upload completed!");
}
}
【问题讨论】: