所以我尝试使用FTP下载文件,并希望显示进度条组件的当前进度。我使用自定义FtpClient
类运行这样的任务:
SaveFileDialog sfd = new SaveFileDialog();
if (sfd.ShowDialog() == true)
{
pBar.Visibility = Visibility.Visible;
string status = "";
string filename = entry.FileName.Text;
await Task.Run(() =>
{
status = client.DownloadFile(filename, sfd.FileName, pBar);
});
statusBox.Text = status.Substring(4);
}
public string DownloadFile(string source, string dest, ProgressBar pBar)
{
FtpWebRequest sizeRequest = CreateRequest(CombinePaths(url, source), WebRequestMethods.Ftp.GetFileSize); // creates FtpWebRequest and assigns method
FtpWebResponse sizeResponse = (FtpWebResponse)sizeRequest.GetResponse();
if (sizeResponse.ContentLength <= 0) // if server does not support SIZE
pBar.IsIndeterminate = true;
else
{
pBar.IsIndeterminate = false; // fails here since progress bar is in the another thread
pBar.Maximum = sizeResponse.ContentLength;
pBar.Value = 0;
}
byte[] buffer = new byte[buffSize];
using (FtpWebResponse dlResponse = (FtpWebResponse)dlRequest.GetResponse())
{
using (Stream stream = dlResponse.GetResponseStream())
{
using (FileStream fs = new FileStream(dest, FileMode.OpenOrCreate))
{
int readCount = stream.Read(buffer, 0, buffSize);
while (readCount > 0)
{
fs.Write(buffer, 0, readCount);
pBar.Value = pBar.Value + readCount;
readCount = stream.Read(buffer, 0, buffSize);
}
}
}
return dlResponse.StatusDescription;
}
有没有办法让这项工作?由于我正在下载并尝试更新用户界面,我不知道有办法做我想做的事情
答案 0 :(得分:0)
pBar.Dispatcher.Invoke(() =>
{
if (GetFileSize(source) <= 0)
pBar.IsIndeterminate = true;
else
{
pBar.IsIndeterminate = false;
pBar.Maximum = GetFileSize(source);
pBar.Value = 0;
}
});
// code...
pBar.Dispatcher.Invoke(() =>
{
pBar.Value = pBar.Value + readCount;
});
使用调度程序更新进度条,完美运行