我正在制作一个WPF应用程序,我使用WebClient从Web服务器下载文件。我的下载工作正常。现在我想将我的e.ProgressPercentage绑定到ProgressBar。我不知道怎么做那个atm。每当我想下载文件时,我都会调用StartDownload来调用DownloadProtocol
class DownloadGameFile
{
public string path { get; set; }
private DownloadTorrentFile DLTorrent;
//List of file that already exist
private List<string> ExistFile = new List<string>();
DirectoryInfo fileInfo;
private string savePath = @"C:\Program Files (x86)\something\Client\package\downloads\";
private bool isDelete = false;
public DownloadGameFile()
{
DLTorrent = new DownloadTorrentFile();
}
public async Task StartDownload(int torrentId)
{
try
{
DLTorrent.DecodeTorrent(torrentId);
downloadGameCover(torrentId);
//Creates a folder to the game
var newdic = Directory.CreateDirectory(savePath + torrentId);
fileInfo = new DirectoryInfo(savePath + torrentId);
//File info from a Directory
FileInfo[] files = fileInfo.GetFiles();
foreach (FileInfo i in files)
{
Console.WriteLine("Files exit " + i);
if (DLTorrent.GameInfomation[i.Name] != i.Length)
{
i.Delete();
isDelete = true;
}
else
{
Console.WriteLine("add files ");
ExistFile.Add(i.Name);
}
}
// Get name form api
string gameName = MainWindow.getGameName(torrentId);
List<Game> games = MyGames.GetList();
games.Add(new Game(torrentId, gameName, "", false, false, "http://cdn.something.com/rental/" + torrentId + ".torrent"));
MyGames.SaveMyGames(games);
//Make a list which file not downloaded yet
var res = DLTorrent.GameInfomation.Keys.Except(ExistFile);
var nFiles = files.Length;
if (nFiles == 0 || !isDelete)
{
nFiles++;
foreach (var x in res)
{
Console.WriteLine("\r {0} out of {1}", nFiles, DLTorrent.GameInfomation.Keys.Count());
await DownloadProtocol("http://cdn.something.com/rental/" + torrentId + "/" + x, savePath + torrentId + "/" + x);
nFiles++;
}
}
else
{
foreach (var x in res)
{
Console.WriteLine("\r {0} out of {1}", nFiles, DLTorrent.GameInfomation.Keys.Count());
await DownloadProtocol("http://cdn.something.com/rental/" + torrentId + "/" + x, savePath + torrentId + "/" + x);
nFiles++;
}
}
}
catch
{
}
}
public async Task DownloadProtocol(string address, string location)
{
Uri Uri = new Uri(address);
using (WebClient client = new WebClient())
{
client.DownloadProgressChanged += (o, e) =>
{
Console.Write("\r{0} Bytes - {1}%", e.BytesReceived, e.ProgressPercentage);
};
client.DownloadFileCompleted += (o, e) =>
{
if (e.Cancelled == true)
{
Console.WriteLine("Download has been canceled.");
}
else
{
Console.WriteLine("Download completed!");
}
};
await client.DownloadFileTaskAsync(Uri, location);
}
}
<ProgressBar x:Name="pb" HorizontalAlignment="Left" Width="150" Height="25" Margin="0,0,0,0" Value="{Binding Path=??}"</ProgressBar>
答案 0 :(得分:0)
在MainWindow
public void UpdateBar(int value)
{
pb.Value=value;
}
然后从MainWindow
client.DownloadProgressChanged += (o, e) =>
{
UpdateBar(e.Percentage);
};
因为它是公开的,所以你可以在课堂上使用它。 这将根据webclient更新下载进度。