public async Task InitializeDownload(Form OwnerForm, string path, List <AbstractFile> DownloadList) { int count = DownloadList.Count, enumerator = 0; CopyProgress window = new CopyProgress("0", count.ToString()); window.Owner = OwnerForm; window.Show(); string ResultPath = String.Empty; foreach (ConcreteFile file in DownloadList) { /*if (DownloadList.Count < 2) * { * ResultPath = path; * } * else * { * ResultPath = path + @"\" + file.FileName; * }*/ ResultPath = (DownloadList.Count < 2) ? path : path + @"\" + file.FileName; using (FileStream fstream = new FileStream(ResultPath, FileMode.CreateNew)) { IDownloadResponse <FileMetadata> GetFile = await client.Files.DownloadAsync(file.FilePath); byte[] FileAsBytes = await GetFile.GetContentAsByteArrayAsync(); await fstream.WriteAsync(FileAsBytes, 0, FileAsBytes.Length); enumerator++; window.RefreshData(enumerator, count); } } }
protected override async Task PerformIO() { IDownloadResponse <FileMetadata> data = await _client.Files.GetThumbnailAsync(ODFileUtils.CombinePaths(Folder, FileName, '/') , size : ThumbnailSize.W128h128.Instance); FileContent = await data.GetContentAsByteArrayAsync(); }
public async Task Download(string folder, string file) { using (var client = new DropboxClient(AccessToken)) { using (IDownloadResponse <FileMetadata> response = await client.Files.DownloadAsync(folder + "/" + file)) { LastDownloadedFile = await response.GetContentAsByteArrayAsync(); } } }
public async Task DownloadFile(string filename, Stream s) { using (DropboxClient client = new DropboxClient(_accessKey)) { IDownloadResponse <FileMetadata> resp = await client.Files.DownloadAsync(filename); Stream ds = await resp.GetContentAsStreamAsync(); await ds.CopyToAsync(s); ds.Dispose(); } }
//All units used here has been unit tested seperately protected override List <string> PerformExecution(Dictionary <string, string> evaluatedValues) { string localToPath; evaluatedValues.TryGetValue("ToPath", out localToPath); string localFromPath; evaluatedValues.TryGetValue("FromPath", out localFromPath); IDropboxSingleExecutor <IDropboxResult> dropBoxDownLoad = new DropBoxDownLoad(localToPath); var dropboxSingleExecutor = GetDropboxSingleExecutor(dropBoxDownLoad); _dropboxClientWrapper = _dropboxClientWrapper ?? new DropboxClientWrapper(GetClient()); var dropboxExecutionResult = dropboxSingleExecutor.ExecuteTask(_dropboxClientWrapper); var dropboxSuccessResult = dropboxExecutionResult as DropboxDownloadSuccessResult; if (dropboxSuccessResult != null) { Response = dropboxSuccessResult.GetDownloadResponse(); var bytes = Response.GetContentAsByteArrayAsync().Result; if (Response.Response.IsFile) { LocalPathManager = new LocalPathManager(localFromPath); var validFolder = LocalPathManager.GetFullFileName(); var fileExist = LocalPathManager.FileExist(); if (fileExist && !OverwriteFile) { throw new Exception(ErrorResource.DropBoxDestinationFileAlreadyExist); } DropboxFile.WriteAllBytes(validFolder, bytes); } return(new List <string> { GlobalConstants.DropBoxSuccess }); } var dropboxFailureResult = dropboxExecutionResult as DropboxFailureResult; if (dropboxFailureResult != null) { Exception = dropboxFailureResult.GetException(); } var executionError = Exception.InnerException?.Message ?? Exception.Message; if (executionError.Contains("not_file")) { executionError = ErrorResource.DropBoxFilePathMissing; } throw new Exception(executionError); }
public async Task <StorageFile> DownloadFileAsync(string remoteFullPath, CancellationToken cancellationToken) { if (!await IsAuthenticatedAsync().ConfigureAwait(false)) { return(null); } try { StorageFile result = await CoreHelper.RetryAsync(async() => { using (await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false)) using (IDownloadResponse <FileMetadata> downloadResponse = await _dropboxClient.Files.DownloadAsync("/" + remoteFullPath).ConfigureAwait(false)) using (Stream remoteFileContentStream = await downloadResponse.GetContentAsStreamAsync().ConfigureAwait(false)) { string fileName = Path.GetFileName(remoteFullPath); var localUserDataFolder = await CoreHelper.GetOrCreateUserDataStorageFolderAsync().ConfigureAwait(false); StorageFile localFile = await localUserDataFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); using (IRandomAccessStream localFileContent = await localFile.OpenAsync(FileAccessMode.ReadWrite)) using (Stream localFileContentStream = localFileContent.AsStreamForWrite()) { await remoteFileContentStream.CopyToAsync(localFileContentStream, bufferSize: TransferBufferSize, cancellationToken).ConfigureAwait(false); await localFileContentStream.FlushAsync(cancellationToken).ConfigureAwait(false); await localFileContent.FlushAsync(); } return(localFile); } }).ConfigureAwait(false); _logger.LogEvent(DownloadFileEvent, $"File downloaded."); return(result); } catch (Exception ex) { _logger.LogFault(DownloadFileFaultEvent, "Unable to download a file.", ex); return(null); } }
public IDropboxResult ExecuteTask(IDropboxClientWrapper client) { try { var downloadArg = new DownloadArg(_path); IDownloadResponse <FileMetadata> uploadAsync = client.DownloadAsync(downloadArg).Result; return(new DropboxDownloadSuccessResult(uploadAsync)); } catch (Exception exception) { Dev2Logger.Error(exception.Message); var hasInnerExc = exception.InnerException != null; if (hasInnerExc) { if (exception.InnerException.Message.Contains("not_found")) { return(new DropboxFailureResult(new DropboxFileNotFoundException())); } return(exception.InnerException.Message.Contains("not_file") ? new DropboxFailureResult(new DropboxPathNotFileFoundException()) : new DropboxFailureResult(exception.InnerException)); } return(new DropboxFailureResult(exception)); } }
protected override async Task PerformIO() { if (!FileExists(_client, ODFileUtils.CombinePaths(Folder, FileName, '/'))) { throw new Exception("File not found."); } IDownloadResponse <FileMetadata> response = await _client.Files.DownloadAsync(ODFileUtils.CombinePaths(Folder, FileName, '/')); DownloadFileSize = response.Response.Size; ulong numChunks = DownloadFileSize / MAX_FILE_SIZE_BYTES + 1; int chunkSize = (int)DownloadFileSize / (int)numChunks; byte[] buffer = new byte[chunkSize]; byte[] finalBuffer = new byte[DownloadFileSize]; int index = 0; using (Stream stream = await response.GetContentAsStreamAsync()) { int length = 0; do { if (DoCancel) { throw new Exception("Operation cancelled by user"); } length = stream.Read(buffer, 0, chunkSize); //Convert each chunk to a MemoryStream. This plays nicely with garbage collection. using (MemoryStream memstream = new MemoryStream()) { memstream.Write(buffer, 0, length); Array.Copy(memstream.ToArray(), 0, finalBuffer, index, length); index += length; OnProgress((double)index / (double)1024 / (double)1024, "?currentVal MB of ?maxVal MB downloaded", (double)DownloadFileSize / (double)1024 / (double)1024, ""); } } while(length > 0); } FileContent = finalBuffer; }
public override async Task <CloudProviderResponse <byte[]> > GetFileInMemory(string path) { try { Logger.Log(LoggerMessageType.Information | LoggerMessageType.VerboseHigh, "DropboxStorageProvider PutFile '{0}'.", path); //we should really download to a temporary location IDownloadResponse <FileMetadata> downloadResponse = await _client.Files.DownloadAsync(path); byte[] data = await downloadResponse.GetContentAsByteArrayAsync(); return(new CloudProviderResponse <byte[]>(data)); } catch (AuthException ae) { Logger.Log(LoggerMessageType.Information | LoggerMessageType.VerboseHigh, "An authorisation error occurred whilst attempting to get file '{0}' from DropboxStorageProvider. {1}", path, ae.Message); return(new CloudProviderResponse <byte[]>(CloudProviderResponse <byte[]> .Response.AuthenticationError, ae)); } catch (DropboxException de) { Logger.Log(LoggerMessageType.Information | LoggerMessageType.VerboseHigh, "An error occurred whilst attempting to get file '{0}' from DropboxStorageProvider. {1}", path, de.Message); if (de.Message.ToLower().Contains("not_found")) { return(new CloudProviderResponse <byte[]>(CloudProviderResponse <byte[]> .Response.NotFound, de)); } else { return(new CloudProviderResponse <byte[]>(CloudProviderResponse <byte[]> .Response.UnknownError, de)); } } catch (Exception ex) { Logger.Log(LoggerMessageType.Information | LoggerMessageType.VerboseHigh, "An unknown error occurred whilst attempting to get file '{0}' from DropboxStorageProvider. {1}", path, ex.Message); return(new CloudProviderResponse <byte[]>(CloudProviderResponse <byte[]> .Response.UnknownError, ex)); } }
/// <summary> /// Reads content of the underlying file as a text string. /// </summary> /// <returns>Content of the underlying file as a text string.</returns> /// <exception cref="AccessDeniedException"></exception> /// <exception cref="DirectoryNotFoundException"></exception> /// <exception cref="FileNotFoundException"></exception> /// <exception cref="PathTooLongException"></exception> /// <exception cref="FileStorageException"></exception> public async Task <string> ReadTextAsync() { try { using (DropboxClient dropboxClient = new DropboxClient(this.accessToken)) using (IDownloadResponse <FileMetadata> response = await dropboxClient.Files.DownloadAsync(this.filepath)) return(await response.GetContentAsStringAsync()); } catch (ApiException <DownloadError> e) { if (e.ErrorResponse.IsPath) { throw new DirectoryNotFoundException($"Directory not found: \"{this.filepath}\". See inner exception for details.", e); } throw new FileStorageException($"Generic file storage exception: \"{this.filepath}\". See inner exception for details.", e); } catch (Exception e) { throw new FileStorageException($"Generic file storage exception: \"{this.filepath}\". See inner exception for details.", e); } }
public DropboxDownloadSuccessResult(IDownloadResponse <FileMetadata> uploadAsync) { _uploadAsync = uploadAsync; }