public async Task DownloadFile(string remotePath, string localPath = null, FileHandler handler = null) { try { var pathKey = localPath ?? remotePath; using (var s3Client = AWSS3Client) { if (handler != null) { _fileHandlers[pathKey] = handler; } var request = new GetObjectRequest { BucketName = ZibaobaoBucket, Key = ConvertToRemotePath(remotePath) }; try { using (var response = await s3Client.GetObjectAsync(request)) { response.WriteObjectProgressEvent += Request_WriteObjectProgressEvent; string content = null; using (var stream = response.ResponseStream) { if (!string.IsNullOrEmpty(localPath)) { ZibaobaoLibContext.Instance.PersistentStorage.SaveContent(localPath, stream); } else { using (var reader = new StreamReader(stream)) { content = reader.ReadToEnd(); } } } if (_fileHandlers.ContainsKey(pathKey)) { _fileHandlers[pathKey].OnFileAvailable(pathKey, content); _fileHandlers.Remove(pathKey); } else { OnFileAvailable?.Invoke(this, new StringEventArgs(pathKey)); } } } catch (AmazonS3Exception s3Exception) { X1LogHelper.Exception(s3Exception); } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("=====ERROR ========"); } }
void File_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { System.Diagnostics.Debug.WriteLine("[Property changed] " + e.PropertyName + " -> " + sender?.GetType().GetProperty(e.PropertyName)?.GetValue(sender, null)); // Update UI text-fields var downloadFile = ((IDownloadFile)sender); if (downloadFile == null) { return; } // Update UI text-fields switch (e.PropertyName) { case nameof(IDownloadFile.Status): X1LogHelper.Log($"{downloadFile.Url} [status]: {downloadFile.Status}"); break; case nameof(IDownloadFile.TotalBytesExpected): X1LogHelper.Verbose($"{downloadFile.Url} [Total length]: {downloadFile.TotalBytesExpected}"); break; case nameof(IDownloadFile.TotalBytesWritten): X1LogHelper.Verbose($"{downloadFile.Url} [downloaded]: {downloadFile.TotalBytesWritten}"); break; } // Update UI if download-status changed. if (e.PropertyName == "Status") { switch (((IDownloadFile)sender).Status) { case DownloadFileStatus.COMPLETED: { X1LogHelper.Log($"{downloadFile.Url} [downloaded as ]: [{downloadFile.DestinationPathName}]"); var path = downloadFile.DestinationPathName; if (path.StartsWith(BaobaoModel.LocalPathPrefix)) { path = path.Substring(BaobaoModel.LocalPathPrefix.Length); } OnFileAvailable?.Invoke(this, new StringEventArgs(path)); } break; } } }