At first I made an application that downloads a file from the entered link and displays information about progress, speed, etc. When I decided to change the application to download several files at the same time, I ran into a problem. So, in the interface there is a listbox in which there are several objects. When you select one of the objects and enter the link to the file, it should start downloading. When selecting another object, information about the previous object should change to the information of the selected one. I can also enter a link to the file there and then track the downloads of the two files by switching between objects. However, when switching information does not change. How to implement it?
Model:
public class Model
{
public WebClient webClient = new WebClient();
public Stopwatch stopWatch = new Stopwatch();
public event Action FileSizeChanged;
public event Action DownloadBytesChanged;
public event Action ProgressPercentageChanged;
public event Action DownloadComplete;
public string Name { get; set; }
public void DownloadFile(string url, bool openAfterDownload)
{
if (webClient.IsBusy)
throw new Exception("The client is busy");
try
{
var startDownloading = DateTime.UtcNow;
webClient.Proxy = null;
if (!SelectFolder(Path.GetFileName(url)+Path.GetExtension(url), out var filePath))
throw DownloadingError();
webClient.DownloadProgressChanged += (o, args) =>
{
ProgressPercentageChanged?.Invoke(args.ProgressPercentage);
FileSizeChanged?.Invoke(args.TotalBytesToReceive);
DownloadBytesChanged?.Invoke(args.BytesReceived, DateTime.UtcNow - startDownloading);
if (args.ProgressPercentage >= 100 && openAfterDownload)
Process.Start(filePath);
};
webClient.DownloadFileCompleted += (o, args) => DownloadComplete?.Invoke();
stopWatch.Start();
webClient.DownloadFileAsync(new Uri(url), filePath);
}
catch (Exception e)
{
throw DownloadingError();
}
}
public void CancelDownloading()
{
webClient.CancelAsync();
webClient.Dispose();
DownloadComplete?.Invoke();
}
private static Exception DownloadingError()
=> new Exception("Downloading error!");
private static bool SelectFolder(string fileName, out string filePath)
{
var saveFileDialog = new SaveFileDialog
{
InitialDirectory = "c:\\",
FileName = fileName,
Filter = "All files (*.*)|*.*"
};
filePath = "";
if (saveFileDialog.ShowDialog() != true) return false;
filePath = saveFileDialog.FileName;
return true;
}
}
ViewModel:
class MainVM : INotifyPropertyChanged
{
private string url;
private RelayCommand downloadCommand;
private RelayCommand cancelCommand;
private double progressBarValue;
private string bytesReceived;
private string bytesTotal;
private string speed;
private string time;
private string error;
private long totalBytes;
private Model selectedGame;
public ObservableCollection Games { get; set; }
public MainVM()
{
Games = new ObservableCollection();
Model Game1 = new Model { Name = "Name1" };
Model Game2 = new Model { Name = "Name2" };
Game1.FileSizeChanged += bytes => BytesTotal = PrettyBytes(totalBytes = bytes);
Game1.DownloadBytesChanged += (bytes, time) =>
{
BytesReceived = PrettyBytes(bytes);
Speed = DownloadingSpeed(bytes, time);
Time = DownloadingTime(bytes, totalBytes, time);
};
Game1.ProgressPercentageChanged += percentage => ProgressBarValue = percentage;
Game1.DownloadComplete += () =>
{
BytesReceived = "";
BytesTotal = "";
Speed = "";
Time = "";
ProgressBarValue = 0;
};
Game2.FileSizeChanged += bytes => BytesTotal = PrettyBytes(totalBytes = bytes);
Game2.DownloadBytesChanged += (bytes, time) =>
{
BytesReceived = PrettyBytes(bytes);
Speed = DownloadingSpeed(bytes, time);
Time = DownloadingTime(bytes, totalBytes, time);
};
Game2.ProgressPercentageChanged += percentage => ProgressBarValue = percentage;
Game2.DownloadComplete += () =>
{
BytesReceived = "";
BytesTotal = "";
Speed = "";
Time = "";
ProgressBarValue = 0;
};
Games.Add(Game1);
Games.Add(Game2);
}
public Model SelectedGame
{
get => selectedGame;
set
{
if (value == selectedGame) return;
selectedGame = value;
OnPropertyChanged(nameof(SelectedGame));
}
}
public string Error
{
get => error;
private set
{
error = value;
OnPropertyChanged(nameof(Error));
}
}
public string URL
{
get => url;
set
{
url = value;
OnPropertyChanged(nameof(URL));
}
}
public bool OpenDownloadedFile { get; set; }
public double ProgressBarValue
{
get => progressBarValue;
set
{
progressBarValue = value;
OnPropertyChanged(nameof(ProgressBarValue));
}
}
public string BytesTotal
{
get => bytesTotal;
private set
{
bytesTotal = value;
OnPropertyChanged(nameof(BytesTotal));
}
}
public string BytesReceived
{
get => bytesReceived;
private set
{
bytesReceived = value;
OnPropertyChanged(nameof(BytesReceived));
}
}
public string Speed
{
get => speed;
private set
{
speed = value;
OnPropertyChanged(nameof(Speed));
}
}
public string Time
{
get => time;
private set
{
time = value;
OnPropertyChanged(nameof(Time));
}
}
public RelayCommand DownloadCommand =>
downloadCommand ??
(downloadCommand = new RelayCommand(DownloadButton_Click));
public RelayCommand CancelCommand =>
cancelCommand ??
(cancelCommand = new RelayCommand(CancelButton_Click));
private void DownloadButton_Click(object obj)
{
if (url == null && url == "") return;
try
{
SelectedGame.DownloadFile(url, OpenDownloadedFile);
}
catch (Exception e)
{
Error = e.Message;
}
}
private void CancelButton_Click(object obj)
{
if (url != null || url != "")
SelectedGame.CancelDownloading();
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string prop = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
}
private static string PrettyBytes(double bytes)
{
if (bytes < 1024)
return bytes + "Bytes";
if (bytes < Math.Pow(1024, 2))
return (bytes / 1024).ToString("F" + 2) + "Kilobytes";
if (bytes < Math.Pow(1024, 3))
return (bytes / Math.Pow(1024, 2)).ToString("F" + 2) + "Megabytes";
if (bytes < Math.Pow(1024, 4))
return (bytes / Math.Pow(1024, 5)).ToString("F" + 2) + "Gygabytes";
return (bytes / Math.Pow(1024, 4)).ToString("F" + 2) + "terabytes";
}
public static string DownloadingSpeed(long received, TimeSpan time)
{
return ((double)received / 1024 / 1024 / time.TotalSeconds).ToString("F" + 2) + " megabytes/sec";
}
public static string DownloadingTime(long received, long total, TimeSpan time)
{
var receivedD = (double) received;
var totalD = (double) total;
return ((totalD / (receivedD / time.TotalSeconds)) - time.TotalSeconds).ToString("F" + 1) + "sec";
}
}
View: