所以我尝试使用进度条直观地显示通过ftp上传文件的进度。 我似乎无法弄清楚为什么,进度条和其他3个标签(labelSpeed,labelPerc,labelUploaded)无效。
非常感谢任何帮助。感谢。
PS:我附上了我的代码snipet供查看。
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!");
}
}
答案 0 :(得分:2)
您正在使用阻止调用UI线程的UploadFile方法。相反,在GUI线程上,应该使用UploadFileAsync来阻止。
可以看到类似WebClient.UploadProgressChanged Event (System.Net)
的示例编辑::这就是我的意思。替换
client.UploadFile(ftpServer + "/" + folder1 + "/" + folder2 + "/" + folder3 + "/" + new FileInfo(filename).Name, "STOR", filename); //<-- uploads image to ftp Directory
带
client.UploadFileAsync(new Uri(ftpServer + "/" + folder1 + "/" + folder2 + "/" + folder3 + "/" + new FileInfo(filename).Name), "STOR", filename); //<-- uploads image to ftp Directory