private async Task ChunkUpload(string dropboxFileName, string fileBaseEncoded) { // var dropboxClient = IsAuthenticateUser(); if (dropboxClient != null) { // Chunk size is 128KB. const int chunkSize = 128 * 1024; // Create a random file of 1MB in size. //var fileContent = new byte[1024 * 1024]; //new Random().NextBytes(fileContent); try { using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(fileBaseEncoded))) { int numChunks = (int)Math.Ceiling((double)stream.Length / chunkSize); byte[] buffer = new byte[chunkSize]; string sessionId = null; for (var idx = 0; idx < numChunks; idx++) { // Console.WriteLine("Start uploading chunk {0}", idx); var byteRead = stream.Read(buffer, 0, chunkSize); using (MemoryStream memStream = new MemoryStream(buffer, 0, byteRead)) { if (idx == 0) { var result = await dropboxClient.Files.UploadSessionStartAsync(body : memStream); sessionId = result.SessionId; } else { UploadSessionCursor cursor = new UploadSessionCursor(sessionId, (ulong)(chunkSize * idx)); if (idx == numChunks - 1) { await dropboxClient.Files.UploadSessionFinishAsync(cursor, new CommitInfo(dropboxFileName), memStream); } else { await dropboxClient.Files.UploadSessionAppendV2Async(cursor, body : memStream); } } } } } } catch (ArgumentException ex) { Linetime.Logging.Debugging.DebugLog(ex); } } }
public static async Task <FileMetadata> UploadChunked(this DropboxClient client, string folder, string fileName, Stream fs, CancellationToken cancellationToken, IProgress <long> progress) { const int chunkSize = 128 * 1024; int chunks = (int)Math.Ceiling((double)fs.Length / chunkSize); byte[] buffer = new byte[chunkSize]; string sessionId = null; FileMetadata resultMetadata = null; var fullDestinationPath = $"{folder}/{fileName}"; for (var i = 0; i < chunks; i++) { if (cancellationToken.IsCancellationRequested) { throw new OperationCanceledException(cancellationToken); } var byteRead = fs.Read(buffer, 0, chunkSize); using (var memStream = new MemoryStream(buffer, 0, byteRead)) { if (i == 0) { var result = await client.Files.UploadSessionStartAsync(body : memStream); sessionId = result.SessionId; } else { UploadSessionCursor cursor = new UploadSessionCursor(sessionId, (ulong)(chunkSize * i)); if (i == chunks - 1) { resultMetadata = await client.Files.UploadSessionFinishAsync(cursor, new CommitInfo(fullDestinationPath), memStream); if (!cancellationToken.IsCancellationRequested) { progress.Report(fs.Length); } } else { await client.Files.UploadSessionAppendV2Async(cursor, body : memStream); if (!cancellationToken.IsCancellationRequested) { progress.Report(i * chunkSize); } } } } } return(resultMetadata); }
/// <summary> /// Uploads a file as multiple chunks with progress events /// </summary> private async Task ChunkUpload(FileStream stream, string dropboxFilePath, int chunkSize, bool overwrite, FileTransferProgressArgs args, CancellationToken cancelToken) { int numChunks = (int)Math.Ceiling((double)stream.Length / chunkSize); byte[] buffer = new byte[chunkSize]; string sessionId = null; for (var idx = 0; idx < numChunks; idx++) { var byteRead = stream.Read(buffer, 0, chunkSize); using (MemoryStream memStream = new MemoryStream(buffer, 0, byteRead)) { if (idx == 0) { var result = await _Dropbox.Files.UploadSessionStartAsync(false, memStream); sessionId = result.SessionId; args.BytesTransfered += (ulong)chunkSize; if (FileTransferProgress != null) { FileTransferProgress(this, args); } } else { UploadSessionCursor cursor = new UploadSessionCursor(sessionId, (ulong)(chunkSize * idx)); if (idx == numChunks - 1) { CommitInfo commit = new CommitInfo(dropboxFilePath, WriteMode.Add.Instance, !overwrite); await _Dropbox.Files.UploadSessionFinishAsync(cursor, commit, memStream); } else { await _Dropbox.Files.UploadSessionAppendV2Async(cursor, false, memStream); args.BytesTransfered += (ulong)chunkSize; if (FileTransferProgress != null) { FileTransferProgress(this, args); } } } } if (cancelToken.IsCancellationRequested) { return; } } }
public override void Upload(string path, string fileName, Stream strDatos) { const int chunkSize = 128 * 1024; int byteRead; int numChunks = (int)Math.Ceiling((double)strDatos.Length / chunkSize); UploadSessionStartResult result; byte[] buffer = new byte[chunkSize]; string sessionId = null; UploadSessionCursor cursor; MemoryStream memStream; Task <UploadSessionStartResult> asyncTaskUploadResult; FileMetadata file = null; byteRead = strDatos.Read(buffer, 0, chunkSize); memStream = new MemoryStream(buffer, 0, byteRead); asyncTaskUploadResult = client.Files.UploadSessionStartAsync(body: memStream); result = asyncTaskUploadResult.Result; memStream.Close(); sessionId = result.SessionId; if (ShowDebugrMessages || System.Diagnostics.Debugger.IsAttached) { Console.WriteLine("Start Upload file {0} at folder {1}", fileName, path); } for (int idx = 1; idx < numChunks; idx++) { if (ShowDebugrMessages || System.Diagnostics.Debugger.IsAttached) { Console.WriteLine("Start uploading chunk {0}", idx); } byteRead = strDatos.Read(buffer, 0, chunkSize); memStream = new MemoryStream(buffer, 0, byteRead); cursor = new UploadSessionCursor(sessionId, (ulong)(chunkSize * idx)); if (idx == numChunks - 1) { file = client.Files.UploadSessionFinishAsync(cursor, new CommitInfo(System.IO.Path.Combine(path, fileName)), memStream).Result; } else { client.Files.UploadSessionAppendV2Async(cursor, body: memStream).Wait(); } memStream.Close(); } }
/// <summary> /// Uploads a big file in chunk. The is very helpful for uploading large file in slow network condition /// and also enable capability to track upload progress. /// </summary> /// <param name="folder">The folder to upload the file.</param> /// <param name="fileName">The name of the file.</param> /// <returns>The Async task.</returns> private async Task ChunkUpload(string remote, string local) { // Chunk size is 128KB. const int ChunkSize = 128 * 1024; AppObjects.Log.Log("Chunk upload file..."); // Create a random file of 1MB in size. var fileContent = new byte[1024 * 1024]; new Random().NextBytes(fileContent); using (var stream = new MemoryStream(fileContent)) { int numChunks = (int)Math.Ceiling((double)stream.Length / ChunkSize); byte[] buffer = new byte[ChunkSize]; string sessionId = null; for (var idx = 0; idx < numChunks; idx++) { AppObjects.Log.Log($"Start uploading chunk {idx}"); var byteRead = stream.Read(buffer, 0, ChunkSize); using (MemoryStream memStream = new MemoryStream(buffer, 0, byteRead)) { if (idx == 0) { var result = await this.dbc.Files.UploadSessionStartAsync(body : memStream); sessionId = result.SessionId; } else { UploadSessionCursor cursor = new UploadSessionCursor(sessionId, (ulong)(ChunkSize * idx)); if (idx == numChunks - 1) { await this.dbc.Files.UploadSessionFinishAsync(cursor, new CommitInfo(remote), memStream); } else { await this.dbc.Files.UploadSessionAppendV2Async(cursor, body : memStream); } } } } AppObjects.Log.Log("ChunkUpload file Done!"); } }
public async void UploadFileToDropbox() { System.Diagnostics.Debug.Write("log start" + Environment.NewLine); string folder, fileName; folder = @"C:\UploadFiles"; fileName = @"200MB.zip"; using (var dbx = new DropboxClient(SysConfig.DBKey)) { const int chunkSize = 128 * 1024; using (FileStream stream = new FileStream(folder + "/" + fileName, FileMode.Open, FileAccess.Read)) { int numChunks = (int)Math.Ceiling((double)stream.Length / chunkSize); byte[] buffer = new byte[chunkSize]; string sessionId = null; for (int i = 0; i < numChunks; i++) { var byteRead = stream.Read(buffer, 0, chunkSize); UploadSessionAppendArg arg = new UploadSessionAppendArg(); using (MemoryStream memStream = new MemoryStream(buffer, 0, byteRead)) { if (i == 0) { var result = await dbx.Files.UploadSessionStartAsync(false, memStream); sessionId = result.SessionId; } else { var cursor = new UploadSessionCursor(sessionId, (ulong)(chunkSize * i)); if (i == numChunks - 1) { await dbx.Files.UploadSessionFinishAsync(cursor, new CommitInfo("/" + fileName), memStream); } else { await dbx.Files.UploadSessionAppendV2Async(cursor, false, memStream); } } } System.Diagnostics.Debug.Write("Chunk " + i.ToString() + " of " + numChunks.ToString() + " Written" + Environment.NewLine); } } } }
/// <summary> /// Uploads a big file in chunk. The is very helpful for uploading large file in slow network condition /// and also enable capability to track upload progerss. /// </summary> /// <param name="client">The Dropbox client.</param> /// <param name="folder">The folder to upload the file.</param> /// <param name="fileName">The name of the file.</param> /// <returns></returns> private async Task ChunkUpload(DropboxClient client, string folder, string fileName) { Console.WriteLine("Chunk upload file..."); // Chunk size is 128KB. const int chunkSize = 128 * 1024; // Create a random file of 1MB in size. var fileContent = new byte[1024 * 1024]; new Random().NextBytes(fileContent); using (var stream = new MemoryStream(fileContent)) { int numChunks = (int)Math.Ceiling((double)stream.Length / chunkSize); byte[] buffer = new byte[chunkSize]; string sessionId = null; for (var idx = 0; idx < numChunks; idx++) { Console.WriteLine("Start uploading chunk {0}", idx); var byteRead = stream.Read(buffer, 0, chunkSize); using (MemoryStream memStream = new MemoryStream(buffer, 0, byteRead)) { if (idx == 0) { var result = await client.Files.UploadSessionStartAsync(body : memStream); sessionId = result.SessionId; } else { UploadSessionCursor cursor = new UploadSessionCursor(sessionId, (ulong)(chunkSize * idx)); if (idx == numChunks - 1) { await client.Files.UploadSessionFinishAsync(cursor, new CommitInfo(folder + "/" + fileName), memStream); } else { await client.Files.UploadSessionAppendV2Async(cursor, body : memStream); } } } } } }
protected override async Task PerformIO() { int numOfChunks = Math.Max(FileContent.Length / MAX_FILE_SIZE_BYTES + 1, 2); //Add 1 so that we are under the max file size limit, since an integer will truncate remainders. int chunkSize = FileContent.Length / numOfChunks; string sessionId = null; int index = 0; for (int i = 1; i <= numOfChunks; i++) { if (DoCancel) { throw new Exception("Operation cancelled by user"); } bool lastChunk = i == numOfChunks; int curChunkSize = chunkSize; if (lastChunk) { curChunkSize = FileContent.Length - index; } using (MemoryStream memStream = new MemoryStream(FileContent, index, curChunkSize)) { if (i == 1) { UploadSessionStartResult result = await _client.Files.UploadSessionStartAsync(false, memStream); sessionId = result.SessionId; } else { UploadSessionCursor cursor = new UploadSessionCursor(sessionId, (ulong)index); if (lastChunk) { //Always forcing Dropbox to overwrite any conflicting files. //Otherwise a Dropbox.Api.Files.UploadSessionFinishError.Path error will be returned by Dropbox if there is a "path/conflict/file/..." await _client.Files.UploadSessionFinishAsync(cursor , new CommitInfo(ODFileUtils.CombinePaths(Folder, FileName, '/'), WriteMode.Overwrite.Instance) , memStream); } else { await _client.Files.UploadSessionAppendV2Async(cursor, false, memStream); } } index += curChunkSize; } OnProgress((double)(chunkSize * i) / (double)1024 / (double)1024, "?currentVal MB of ?maxVal MB uploaded", (double)FileContent.Length / (double)1024 / (double)1024, ""); } }
private async Task <FileMetadata> UploadFileInChunksAsync(int chunksCount, Stream localFileContentStream, string fileName) { byte[] buffer = new byte[TransferBufferSize]; string sessionId = null; FileMetadata uploadResult = null; for (var idx = 0; idx < chunksCount; idx++) { var byteRead = localFileContentStream.Read(buffer, 0, TransferBufferSize); using (MemoryStream memStream = new MemoryStream(buffer, 0, byteRead)) { if (idx == 0) { var result = await _dropboxClient.Files.UploadSessionStartAsync(body : memStream).ConfigureAwait(false); sessionId = result.SessionId; if (string.IsNullOrEmpty(sessionId)) { return(null); } } else { UploadSessionCursor cursor = new UploadSessionCursor(sessionId, (ulong)(TransferBufferSize * idx)); if (idx == chunksCount - 1) { uploadResult = await _dropboxClient.Files.UploadSessionFinishAsync( cursor, new CommitInfo( path : "/" + fileName, mode : WriteMode.Overwrite.Instance), memStream) .ConfigureAwait(false); } else { await _dropboxClient.Files.UploadSessionAppendV2Async(cursor, body : memStream).ConfigureAwait(false); } } } } return(uploadResult); }
private async Task SaveAsync(string directory, string file) { var path = _path; path += directory; path += "/"; path += Path.GetFileName(file); string sessionId = null; // upload in chunks with sessions var buffer = new byte[128 * 1024]; using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read)) { _logger.Log(_config.Name, LoggerPriorities.Verbose, "Uploading file {0} with size {1:#,##0.00} kb to directory {2}.", file, fileStream.Length / 1024, directory); while (true) { var byteRead = fileStream.Read(buffer, 0, buffer.Length); using (var memoryStream = new MemoryStream(buffer, 0, byteRead)) { if (sessionId == null) { sessionId = (await _client.Files.UploadSessionStartAsync(body: memoryStream)).SessionId; } else { var cursor = new UploadSessionCursor(sessionId, (ulong)(fileStream.Position - byteRead)); if (byteRead == buffer.Length) { await _client.Files.UploadSessionAppendV2Async(cursor, body : memoryStream); } else { await _client.Files.UploadSessionFinishAsync(cursor, new CommitInfo(path, WriteMode.Overwrite.Instance), memoryStream); break; } } } } } }
/// <summary> /// Uploads a big file in chunk. The is very helpful for uploading large file in slow network condition /// and also enable capability to track upload progerss. /// </summary> /// <param name="client">The Dropbox client.</param> /// <param name="folder">The folder to upload the file.</param> /// <param name="fileName">The name of the file.</param> /// <returns></returns> private static async Task ChunkUpload(DropboxClient client, string folder, string fileName, FileStream stream) { // Chunk size is 128KB. const int chunkSize = 128 * 1024; using (stream) { int numChunks = (int)Math.Ceiling((double)stream.Length / chunkSize); byte[] buffer = new byte[chunkSize]; string sessionId = null; for (var idx = 0; idx < numChunks; idx++) { var byteRead = stream.Read(buffer, 0, chunkSize); using (MemoryStream memStream = new MemoryStream(buffer, 0, byteRead)) { if (idx == 0) { var result = await client.Files.UploadSessionStartAsync(body : memStream); sessionId = result.SessionId; } else { UploadSessionCursor cursor = new UploadSessionCursor(sessionId, (ulong)(chunkSize * idx)); if (idx == numChunks - 1) { await client.Files.UploadSessionFinishAsync(cursor, new CommitInfo(folder + "/" + fileName), memStream); } else { await client.Files.UploadSessionAppendV2Async(cursor, body : memStream); } } } } } }
/// <summary> /// Uploads a big file in chunk. The is very helpful for uploading large file in slow network condition /// and also enable capability to track upload progerss. /// </summary> /// <param name="client">The Dropbox client.</param> /// <param name="sourceFile">Byte array to upload.</param> /// <param name="location">Location on dropbox.</param> /// <returns></returns> public static async Task ChunkUpload(DropboxClient client, string sourceFile, string location) { Console.WriteLine($"{DateTime.Now} Chunk upload file..."); const int chunkSize = 1024 * 1024 * 10; using (FileStream stream = File.OpenRead(sourceFile)) { int numChunks = (int)Math.Ceiling((double)stream.Length / chunkSize); byte[] buffer = new byte[chunkSize]; string sessionId = null; for (int idx = 0; idx < numChunks; idx++) { Console.WriteLine($"{DateTime.Now} Start uploading chunk {idx}"); int byteRead = stream.Read(buffer, 0, chunkSize); using (MemoryStream memStream = new MemoryStream(buffer, 0, byteRead)) { if (idx == 0) { UploadSessionStartResult result = await client.Files.UploadSessionStartAsync(body : memStream); sessionId = result.SessionId; } else { UploadSessionCursor cursor = new UploadSessionCursor(sessionId, (ulong)(chunkSize * idx)); if (idx == numChunks - 1) { await client.Files.UploadSessionFinishAsync(cursor, new CommitInfo(location, WriteMode.Overwrite.Instance), memStream); } else { await client.Files.UploadSessionAppendV2Async(cursor, body : memStream); } } } } } }
public async Task UploadAsync(string file_path, string file_name) { using var client = new DropboxClient(dropboxToken); const int chunkSize = 50 * 1024 * 1024; var fileContent = System.IO.File.ReadAllBytes(file_path); new Random().NextBytes(fileContent); using var stream = new MemoryStream(fileContent); var numChunks = (int)Math.Ceiling((double)stream.Length / chunkSize); byte[] buffer = new byte[chunkSize]; string sessionId = null; for (var idx = 0; idx < numChunks; idx++) { var byteRead = stream.Read(buffer, 0, chunkSize); using MemoryStream memStream = new MemoryStream(buffer, 0, byteRead); if (idx == 0) { var result = await client.Files.UploadSessionStartAsync(body : memStream); sessionId = result.SessionId; } else { UploadSessionCursor cursor = new UploadSessionCursor(sessionId, (ulong)(chunkSize * idx)); if (idx == numChunks - 1) { await client.Files.UploadSessionFinishAsync(cursor, new CommitInfo(dropboxFolder + file_name), memStream); } else { await client.Files.UploadSessionAppendV2Async(cursor, body : memStream); } } } }
static async Task UploadBigFileToDropbox(DropboxClient client, string filePath, string destinationPath) { var fileContent = File.ReadAllBytes(filePath); using (var stream = new MemoryStream(fileContent)) { int numChunks = (int)Math.Ceiling((double)stream.Length / BigFileChunkSize); byte[] buffer = new byte[BigFileChunkSize]; string sessionId = null; for (var idx = 0; idx < numChunks; idx++) { Console.WriteLine("Start uploading chunk {0}", idx); var byteRead = stream.Read(buffer, 0, BigFileChunkSize); using (MemoryStream memStream = new MemoryStream(buffer, 0, byteRead)) { if (idx == 0) { var result = await client.Files.UploadSessionStartAsync(body : memStream); sessionId = result.SessionId; } else { UploadSessionCursor cursor = new UploadSessionCursor(sessionId, (ulong)(BigFileChunkSize * idx)); if (idx == numChunks - 1) { await client.Files.UploadSessionFinishAsync(cursor, new CommitInfo(destinationPath), memStream); Console.WriteLine("Uploaded successfully to dropbox."); } else { await client.Files.UploadSessionAppendV2Async(cursor, body : memStream); } } } } } }
static async Task ChunkUpload(String path, Stream stream, int chunkSize) { var key = ConfigurationManager.AppSettings["DropboxKey"]; using (var dbx = new DropboxClient(key)) { ulong numChunks = (ulong)Math.Ceiling((double)stream.Length / chunkSize); byte[] buffer = new byte[chunkSize]; string sessionId = null; for (ulong idx = 0; idx < numChunks; idx++) { var byteRead = stream.Read(buffer, 0, chunkSize); using (var memStream = new MemoryStream(buffer, 0, byteRead)) { if (idx == 0) { var result = await dbx.Files.UploadSessionStartAsync(false, memStream); sessionId = result.SessionId; } else { var cursor = new UploadSessionCursor(sessionId, (ulong)chunkSize * idx); if (idx == numChunks - 1) { FileMetadata fileMetadata = await dbx.Files.UploadSessionFinishAsync(cursor, new CommitInfo(path), memStream); Console.WriteLine(fileMetadata.PathDisplay); } else { await dbx.Files.UploadSessionAppendV2Async(cursor, false, memStream); } } } } } }
/// <summary> /// /// </summary> /// <param name="client"></param> /// <param name="folder"></param> /// <param name="sourcePath"></param> public async void UpLoadFile(DropboxClient client, string folder, string sourcePath) { // Chunk size is 128KB. const int chunkSize = 128 * 1024; if (!System.IO.File.Exists(sourcePath)) { return; } System.IO.FileInfo info = new System.IO.FileInfo(sourcePath); long fileSize = info.Length; string fileName = System.IO.Path.GetFileName(sourcePath); string path; if (string.IsNullOrEmpty(folder)) { path = "/" + fileName; } else { path = folder + "/" + fileName; } //using (var stream = new MemoryStream(fileContent)) using (var stream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { int numChunks = (int)Math.Ceiling((double)stream.Length / chunkSize); byte[] buffer = new byte[chunkSize]; string sessionId = null; long currentSize = 0; for (var idx = 0; idx < numChunks; idx++) { var byteRead = stream.Read(buffer, 0, chunkSize); ProgressEvent?.Invoke(currentSize, fileSize); using (MemoryStream memStream = new MemoryStream(buffer, 0, byteRead)) { if (idx == 0) { if (numChunks == 1) { //小文件 await client.Files.UploadAsync(path, body : memStream); } else { var result = await client.Files.UploadSessionStartAsync(false, memStream); sessionId = result.SessionId; } } else { UploadSessionCursor cursor = new UploadSessionCursor(sessionId, (ulong)(chunkSize * idx)); if (idx == numChunks - 1) { await client.Files.UploadSessionFinishAsync(cursor, new CommitInfo(path), memStream); } else { await client.Files.UploadSessionAppendV2Async(cursor, false, memStream); } } } } FinishedEvent?.Invoke(); } }
private async Task <string> ChunkUploadStreamAsync(Stream stream, string filepath, ulong size, DateTime lastModified) { int chunkSize = this.context.HttpChunkSize; int chunkCount = (int)Math.Ceiling((double)size / chunkSize); string serverRev = null; byte[] buffer = new byte[chunkSize]; string sessionId = null; var commitInfo = new CommitInfo(filepath, WriteMode.Overwrite.Instance, false, lastModified); DateTime start = DateTime.Now; for (var index = 0; index < chunkCount; index++) { var read = await stream .ReadAsync(buffer, 0, chunkSize) .WithTimeout(TimeSpan.FromSeconds(this.context.HttpReadTimeoutInSeconds)); var offset = (ulong)(chunkSize * index); this.ProgressUpdate(filepath, size, offset, start); using (MemoryStream memoryStream = new MemoryStream(buffer, 0, read)) { if (chunkCount == 1) { var result = await this.Client.Files .UploadAsync(commitInfo, memoryStream) .WithTimeout(TimeSpan.FromSeconds(this.context.HttpWriteTimeoutInSeconds)); serverRev = result.Rev; } else if (index == 0) { var result = await this.Client.Files .UploadSessionStartAsync(body : memoryStream) .WithTimeout(TimeSpan.FromSeconds(this.context.HttpWriteTimeoutInSeconds)); sessionId = result.SessionId; } else { UploadSessionCursor cursor = new UploadSessionCursor(sessionId, offset); bool isLastChunk = index == chunkCount - 1; if (!isLastChunk) { await this.Client.Files .UploadSessionAppendV2Async(cursor, body : memoryStream) .WithTimeout(TimeSpan.FromSeconds(this.context.HttpWriteTimeoutInSeconds)); } else { var result = await this.Client.Files .UploadSessionFinishAsync(cursor, commitInfo, memoryStream) .WithTimeout(TimeSpan.FromSeconds(this.context.HttpWriteTimeoutInSeconds)); serverRev = result.Rev; } } } } return(serverRev); }
async Task <int> Upload() { using (Service1Client client = new Service1Client()) { GetFileRecordResponse dbxKey = client.GetFileRecord(); if (dbxKey.Errored) { return(-1); } string logoPath = Server.MapPath("~/TemporaryFolder"); string filename = FileInput.FileName; if (Directory.Exists(logoPath)) { System.IO.DirectoryInfo di = new DirectoryInfo(logoPath); di.Delete(true); } DirectorySecurity securityRules = new DirectorySecurity(); securityRules.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow)); DirectoryInfo dir = Directory.CreateDirectory(logoPath); dir.SetAccessControl(securityRules); using (var dbx = new DropboxClient(SysConfig.DBKey)) { string folder = Path.GetDirectoryName(Server.MapPath(FileInput.FileName)); // path to containing folder of file to be uploaded string fileName = FileInput.FileName; // name of file to be uploaded FileStream fs = new FileStream(@logoPath + "\\data.dat", FileMode.CreateNew, FileAccess.ReadWrite); FileInput.PostedFile.InputStream.CopyTo(fs); fs.Close(); //128 kb chunks const int chunkSize = 128 * 1024; // create filestream using (FileStream stream = new FileStream(@logoPath + "\\data.dat", FileMode.Open, FileAccess.ReadWrite)) //using (FileStream stream = File.Create(logoPath)) { //FileInput.PostedFile.InputStream.CopyTo(stream); // generate information for loop int numChunks = (int)Math.Ceiling((double)stream.Length / chunkSize); byte[] buffer = new byte[chunkSize]; string sessionId = null; // chunk sessions pValue = numChunks; System.Diagnostics.Debug.WriteLine(numChunks.ToString()); for (int i = 0; i < numChunks; i++) { Console.WriteLine(i.ToString() + " / " + numChunks.ToString()); var byteRead = stream.Read(buffer, 0, chunkSize); UploadSessionAppendArg arg = new UploadSessionAppendArg(); using (MemoryStream memStream = new MemoryStream(buffer, 0, byteRead)) { if (i == 0) { var result = await dbx.Files.UploadSessionStartAsync(false, memStream); sessionId = result.SessionId; } else { var cursor = new UploadSessionCursor(sessionId, (ulong)(chunkSize * i)); Status.Text = i.ToString() + " / " + numChunks.ToString(); System.Diagnostics.Debug.WriteLine(i.ToString() + " / " + numChunks.ToString()); if (i == numChunks - 1) { await dbx.Files.UploadSessionFinishAsync (cursor, new CommitInfo("/" + fileName), memStream); } else { await dbx.Files.UploadSessionAppendV2Async(cursor, false, memStream); } } } } } // file upload finished log new file name InsertFileRecordResponse frResp = client.InsertFileRecord(new InsertFileRecordRequest() { FileName = FileInput.PostedFile.FileName }); if (frResp.Errored) { // handle it ErreurMessage.Text = "Error"; return(0); } // if the file is a new version delete the old version if (frResp.DeleteOldFile) { await dbx.Files.DeleteAsync(new DeleteArg("/" + frResp.OldFileName)); } ///DELETE THE TEMPORARY FILE /// if (Directory.Exists(logoPath)) { System.IO.DirectoryInfo di = new DirectoryInfo(logoPath); di.Delete(true); } Status.Text = "100%"; EndMessage.Text = "Upload Completed"; EndMessage.Visible = true; theProgressBar.Visible = false; return(0); } } }
private static void uploadZipFile(string origen, string folder) { FileStream stream = null; try { clientConf = new DropboxClientConfig("ScandaV1"); client = new DropboxClient(APITOKEN); FileInfo info = new FileInfo(origen); string extension = info.Extension; float size = info.Length / (B_TO_MB * 1.0f); long nChunks = info.Length / CHUNK_SIZE; stream = new FileStream(origen, FileMode.Open); string nombre = info.Name; if (nChunks == 0) { var subidaS = client.Files.UploadAsync("/" + folder + "/" + nombre, OVERWRITE, false, body: stream); subidaS.Wait(); Console.WriteLine(subidaS.Result.AsFile.Size); stream.Close(); } else { byte[] buffer = new byte[CHUNK_SIZE]; string sessionId = null; for (var idx = 0; idx <= nChunks; idx++) { var byteRead = stream.Read(buffer, 0, CHUNK_SIZE); using (var memSream = new MemoryStream(buffer, 0, byteRead)) { if (idx == 0) { var result = client.Files.UploadSessionStartAsync(body: memSream); result.Wait(); sessionId = result.Result.SessionId; } else { var cursor = new UploadSessionCursor(sessionId, (ulong)(CHUNK_SIZE * idx)); if (idx == nChunks) { var x = client.Files.UploadSessionFinishAsync(cursor, new CommitInfo("/" + folder + "/" + nombre), memSream); x.Wait(); } else { var x = client.Files.UploadSessionAppendAsync(cursor, memSream); x.Wait(); } } } } } } catch (OutOfMemoryException) { Console.WriteLine("Se acabo la memoria"); } catch (FileNotFoundException) { Console.WriteLine("No existe el archivo"); } catch (AggregateException ex) //Excepciones al vuelo { Console.WriteLine("Tarea Cancelada"); } catch (Exception ex) { Console.WriteLine(ex); } if (stream != null) { stream.Close(); stream.Dispose(); } }
private async Task ChunkUpload(String targetpath, FileStream sourceFileStream, int chunkSize) { int numChunks = (int)Math.Ceiling((double)sourceFileStream.Length / chunkSize); LogMessage(string.Format("Number of chunks calculated: {0}", numChunks.ToString())); byte[] buffer = new byte[chunkSize]; string sessionId = null; for (var idx = 0; idx < numChunks; idx++) { var byteRead = sourceFileStream.Read(buffer, 0, chunkSize); using (var memSream = new MemoryStream(buffer, 0, byteRead)) { if (idx == 0) { LogMessage(string.Format("Chunk {0}: Commencing UploadSessionStartAsync", idx.ToString())); try { var result = await this._client.Files.UploadSessionStartAsync(memSream); sessionId = result.SessionId; } catch (Exception ex) { LogErrorAction(string.Format("ERROR: DropBoxClient UploadSessionStartAsync error - {0}", ex.Message)); } LogMessage(string.Format("Chunk {0}: Session Id determined as [{1}]", idx.ToString(), sessionId)); } else { var cursor = new UploadSessionCursor(sessionId, (ulong)(chunkSize * idx)); if (idx == numChunks - 1) { LogMessage(string.Format("Chunk {0}: Commencing UploadSessionFinishAsync", idx.ToString())); LogMessage(string.Format("Chunk {0}: Cursor Offset - {1}", idx.ToString(), cursor.Offset.ToString())); try { await this._client.Files.UploadSessionFinishAsync(cursor, new CommitInfo(targetpath), memSream); } catch (Exception ex) { LogErrorAction(string.Format("ERROR: DropBoxClient UploadSessionFinishAsync error - {0}", ex.Message)); } LogMessage(string.Format("Chunk {0}: Final Chunk uploaded", idx.ToString())); } else { LogMessage(string.Format("Chunk {0}: Commencing UploadSessionAppendAsync", idx.ToString())); LogMessage(string.Format("Chunk {0}: Cursor Offset - {1}", idx.ToString(), cursor.Offset.ToString())); try { await this._client.Files.UploadSessionAppendAsync(cursor, memSream); } catch (Exception ex) { LogErrorAction(string.Format("ERROR: DropBoxClient UploadSessionAppendAsync error - {0}", ex.Message)); } LogMessage(string.Format("Chunk {0}: Chunk uploaded", idx.ToString())); } } } } LogMessage("Finishing chunk session"); }
public async Task UploadFile(LocalPath localPath, CancellationToken token, IProgress <double> progress = null) { using (OperationExecutionContext.Instance.IgnoreChangesTo(localPath)) { token.ThrowIfCancellationRequested(); var serverPath = localPath.ToServerPath(); var fileInfo = new FileInfo(localPath.Value); var lastWriteTimeLocal = fileInfo.LastWriteTimeUtc; var fileMetadata = (await this.GetFileMetadata(serverPath, token)); var lastWriteTimeServer = fileMetadata?.ClientModified; if (lastWriteTimeLocal.AlmostEquals(lastWriteTimeServer)) { progress?.Report(100); return; } using (var fileStream = new FileStream(localPath.Value, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, BufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan)) { using (var encryptor = new CipherStreamEncryptor(fileStream)) { encryptor.AddEncryptedValue(OriginalFileNameKey, localPath.ToUniversalPath().Value, this.credentials.GetRecepientId(), this.credentials.PublicKey); var contentInfo = encryptor.Init( this.credentials.GetRecepientId(), this.credentials.PublicKey, BufferSize); var result = await this.client.Files.UploadSessionStartAsync(false, new MemoryStream(contentInfo)); var sessionId = result.SessionId; ulong written = (ulong)contentInfo.Length; while (encryptor.HasMore()) { token.ThrowIfCancellationRequested(); var chunk = await encryptor.GetChunk(); var cursor = new UploadSessionCursor(sessionId, written); if (encryptor.HasMore()) { await this.client.Files.UploadSessionAppendV2Async(cursor, false, new MemoryStream(chunk)); written += (ulong)chunk.Length; progress?.Report(100.0 * written / fileStream.Length); } else { await this.client.Files.UploadSessionFinishAsync( cursor, new CommitInfo(serverPath.Value, mode : WriteMode.Overwrite.Instance, clientModified : lastWriteTimeLocal.Truncate()), new MemoryStream(chunk)); progress?.Report(100); } } } } } }
/// <summary> /// 批次上傳大檔案,必須要大於 CHUNK_SIZE。僅會檢查檔案大小是否夠大。 /// </summary> private async Task <CloudStorageFile> UploadBigFile(string filePath, string parentFolder, CancellationToken ct) { FileInfo fileInfo = new FileInfo(filePath); // file size must larger than 1 chunk size long fileSize = fileInfo.Length; if (fileSize <= CHUNK_SIZE) { return(null); } using (FileStream fileStream = new FileStream(filePath, FileMode.Open)) { byte[] buffer = new byte[CHUNK_SIZE]; long uploaded = 0; string sessionId; // read first chunk from file int length = await fileStream.ReadAsync(buffer, 0, CHUNK_SIZE, ct); // upload first chunk using (MemoryStream firstStream = new MemoryStream(buffer, 0, length, false)) { var startResult = await dropboxClient.Files.UploadSessionStartAsync(body : firstStream); sessionId = startResult.SessionId; firstStream.Close(); } // update progress bar of first chunk OnProgressChanged(length); uploaded += length; // upload middle chunks while (true) { // check cancel if (ct.IsCancellationRequested) { throw new TaskCanceledException("Upload cancelled."); } // read next chunk from file length = await fileStream.ReadAsync(buffer, 0, CHUNK_SIZE, ct); if (length <= 0) { break; } // if we reach last chung, don't upload now! if (uploaded + length >= fileSize) { break; } // upload each chunk using (MemoryStream tempStream = new MemoryStream(buffer, 0, length, false)) { UploadSessionCursor cursor = new UploadSessionCursor(sessionId, (ulong)uploaded); await dropboxClient.Files.UploadSessionAppendV2Async(cursor, body : tempStream); tempStream.Close(); } // Update progress bar OnProgressChanged(length); uploaded += length; } // ending upload session UploadSessionCursor endCursor = new UploadSessionCursor(sessionId, (ulong)uploaded); // prepare file info if (!parentFolder.EndsWith("/")) { parentFolder += "/"; } parentFolder += Path.GetFileName(filePath); CommitInfo info = new CommitInfo(parentFolder, autorename: true); // do last session FileMetadata finishResult; using (MemoryStream tempStream = new MemoryStream(buffer, 0, length, false)) { finishResult = await dropboxClient.Files.UploadSessionFinishAsync(endCursor, info, tempStream); Console.WriteLine("Finished large file: " + finishResult.PathDisplay); } // update last progress OnProgressChanged(length); fileStream.Close(); // return new file info CloudStorageFile cloudFile = new CloudStorageFile() { Id = finishResult.Id, ModifiedTime = finishResult.ServerModified, Name = finishResult.Name, Size = (long)finishResult.Size }; return(cloudFile); } }
/// <summary> /// Uploads a big file in chunk. The is very helpful for uploading large file in slow network condition /// and also enable capability to track upload progerss. /// </summary> /// <param name="client">The Dropbox client.</param> /// <param name="folder">The folder to upload the file.</param> /// <param name="fileName">The name of the file.</param> /// <returns></returns> private async Task ChunkUpload(DropboxClient client, string folder, string fileName) { Console.WriteLine("Chunk upload file..."); // Chunk size is 128KB. const int chunkSize = 128 * 1024; // Create a random file of 1MB in size. var fileContent = new byte[1024 * 1024]; new Random().NextBytes(fileContent); using (var stream = new MemoryStream(fileContent)) { int numChunks = (int)Math.Ceiling((double)stream.Length / chunkSize); byte[] buffer = new byte[chunkSize]; string sessionId = null; for (var idx = 0; idx < numChunks; idx++) { Console.WriteLine("Start uploading chunk {0}", idx); var byteRead = stream.Read(buffer, 0, chunkSize); using (MemoryStream memStream = new MemoryStream(buffer, 0, byteRead)) { if (idx == 0) { var result = await client.Files.UploadSessionStartAsync(memStream); sessionId = result.SessionId; } else { UploadSessionCursor cursor = new UploadSessionCursor(sessionId, (ulong)(chunkSize * idx)); if (idx == numChunks - 1) { await client.Files.UploadSessionFinishAsync(cursor, new CommitInfo(folder + "/" + fileName), memStream); } else { await client.Files.UploadSessionAppendAsync(cursor, memStream); } } } } } }
/// <summary> /// <para>Finish an upload session and save the uploaded data to the given file /// path.</para> /// </summary> /// <param name="cursor">Contains the upload session ID and the offset.</param> /// <param name="commit">Contains the path and other optional modifiers for the /// commit.</param> /// <param name="body">The document to upload</param> /// <returns>The task that represents the asynchronous send operation. The TResult /// parameter contains the response from the server.</returns> /// <exception cref="Dropbox.Api.ApiException{UploadSessionFinishError}">Thrown if /// there is an error processing the request; This will contain a <see /// cref="UploadSessionFinishError"/>.</exception> public t.Task<FileMetadata> UploadSessionFinishAsync(UploadSessionCursor cursor, CommitInfo commit, io.Stream body) { var uploadSessionFinishArg = new UploadSessionFinishArg(cursor, commit); return this.UploadSessionFinishAsync(uploadSessionFinishArg, body); }
/// <summary> /// <para>Append more data to an upload session.</para> /// </summary> /// <param name="sessionId">The upload session ID (returned by <see /// cref="Dropbox.Api.Files.Routes.FilesRoutes.UploadSessionStartAsync" />).</param> /// <param name="offset">The amount of data that has been uploaded so far. We use this /// to make sure upload data isn't lost or duplicated in the event of a network /// error.</param> /// <param name="body">The document to upload</param> /// <returns>The task that represents the asynchronous send operation.</returns> /// <exception cref="Dropbox.Api.ApiException{UploadSessionLookupError}">Thrown if /// there is an error processing the request; This will contain a <see /// cref="UploadSessionLookupError"/>.</exception> public t.Task UploadSessionAppendAsync(string sessionId, ulong offset, io.Stream body) { var uploadSessionCursor = new UploadSessionCursor(sessionId, offset); return this.UploadSessionAppendAsync(uploadSessionCursor, body); }
/// <summary> /// <para>Append more data to an upload session.</para> /// </summary> /// <param name="uploadSessionCursor">The request parameters</param> /// <param name="body">The content to upload.</param> /// <returns>The task that represents the asynchronous send operation.</returns> /// <exception cref="Dropbox.Api.ApiException{UploadSessionLookupError}">Thrown if /// there is an error processing the request; This will contain a <see /// cref="UploadSessionLookupError"/>.</exception> public t.Task UploadSessionAppendAsync(UploadSessionCursor uploadSessionCursor, io.Stream body) { return this.Transport.SendUploadRequestAsync<UploadSessionCursor, enc.Empty, UploadSessionLookupError>(uploadSessionCursor, body, "content", "/files/upload_session/append", UploadSessionCursor.Encoder, enc.EmptyDecoder.Instance, UploadSessionLookupError.Decoder); }
/// <summary> /// <para>Begins an asynchronous send to the upload session append route.</para> /// </summary> /// <param name="uploadSessionCursor">The request parameters.</param> /// <param name="body">The content to upload.</param> /// <param name="callback">The method to be called when the asynchronous send is /// completed.</param> /// <param name="state">A user provided object that distinguished this send from other /// send requests.</param> /// <returns>An object that represents the asynchronous send request.</returns> public sys.IAsyncResult BeginUploadSessionAppend(UploadSessionCursor uploadSessionCursor, io.Stream body, sys.AsyncCallback callback, object state = null) { var task = this.UploadSessionAppendAsync(uploadSessionCursor, body); return enc.Util.ToApm(task, callback, state); }
private static async Task <bool> uploadZipFile(string origen, string folder, Status status) { FileStream stream = null; try { clientConf = new DropboxClientConfig("ScandaV1"); client = new DropboxClient(APITOKEN); FileInfo info = new FileInfo(origen); status.upload.total = ((info.Length * 1)) / (B_TO_MB * 1.0f) + ""; //Esta en bytes para convertirlos en megas /1024d)/1024d await Logger.sendLog(string.Format("Peso total del archivo es de {0} en megas {1}", info.Length, status.upload.total), "T"); string extension = info.Extension; float size = info.Length / (B_TO_MB * 1.0f); long nChunks = info.Length / CHUNK_SIZE; stream = new FileStream(origen, FileMode.Open); { string nombre = info.Name; if (nChunks == 0) { status.upload.chunk = "0"; await status.uploadStatusFile(status.upload); var subidaS = await client.Files.UploadAsync("/" + folder + "/" + nombre, OVERWRITE, false, body : stream); //subidaS.Wait(); //Console.WriteLine(subidaS.Result.AsFile.Size); //stream.Close(); status.upload.chunk = status.upload.total; status.upload.status = 3; await status.uploadStatusFile(status.upload); } else { byte[] buffer = new byte[CHUNK_SIZE]; string sessionId = null; for (var idx = 0; idx <= nChunks; idx++) { status.upload.status = 2; var byteRead = stream.Read(buffer, 0, CHUNK_SIZE); status.upload.chunk = (idx * (CHUNK_SIZE / 1024d) / 1024d) + ""; //status.upload.chunk = idx.ToString(); //status.upload.total = nChunks.ToString(); MemoryStream memSream = new MemoryStream(buffer, 0, byteRead); try { if (idx == 0) { status.upload.status = 1; //var result = client.Files.UploadSessionStartAsync(body: memSream); //result.Wait(); var result = await client.Files.UploadSessionStartAsync(body : memSream); sessionId = result.SessionId; await Logger.sendLog(string.Format("{0} | {1} | {2}", "", "Servicio de windows ejecutandose ", "Scanda.Service.DBProtector.StartUpload"), "T"); await status.uploadStatusFile(status.upload); } else { ulong trans = (ulong)CHUNK_SIZE * (ulong)idx; var cursor = new UploadSessionCursor(sessionId, trans); await status.uploadStatusFile(status.upload); if (idx == nChunks) { //var x = client.Files.UploadSessionFinishAsync(cursor, new CommitInfo("/" + folder + "/" + nombre), memSream); //x.Wait(); var x = await client.Files.UploadSessionFinishAsync(cursor, new CommitInfo("/" + folder + "/" + nombre), memSream); status.upload.status = 3; await status.uploadStatusFile(status.upload); } else { //var x = client.Files.UploadSessionAppendAsync(cursor, memSream); //x.Wait(); //var x = await client.Files.UploadSessionAppendAsync(cursor, memSream); //await client.Files.UploadSessionAppendV2Async(new UploadSessionAppendArg(cursor), memSream); await client.Files.UploadSessionAppendAsync(cursor, memSream); await status.uploadStatusFile(status.upload); // x.Wait(); //await client.Files.UploadSessionAppendV2Async(new UploadSessionAppendArg(cursor), memSream); } } } catch (Exception ex) { await Logger.sendLog(string.Format("{0} | {1} | {2}", ex.Message, ex.StackTrace, "Scanda.AppTray.ScandaConector.uploadZipFile"), "E"); Console.WriteLine("Error En el Upload"); return(false); } finally { memSream.Dispose(); } } } } return(true); } catch (OutOfMemoryException ex) { await Logger.sendLog(string.Format("{0} | {1} | {2}", ex.Message, ex.StackTrace, "ScandaConector.uploadZipFile"), "E"); Console.WriteLine("Se acabo la memoria"); return(false); } catch (FileNotFoundException ex) { await Logger.sendLog(string.Format("{0} | {1} | {2}", ex.Message, ex.StackTrace, "ScandaConector.uploadZipFile"), "E"); Console.WriteLine("No existe el archivo"); return(false); } catch (AggregateException ex) //Excepciones al vuelo { await Logger.sendLog(string.Format("{0} | {1} | {2}", ex.Message, ex.StackTrace, "ScandaConector.uploadZipFile"), "E"); Console.WriteLine("Tarea Cancelada"); return(false); } catch (Exception ex) { await Logger.sendLog(string.Format("{0} | {1} | {2}", ex.Message, ex.StackTrace, "ScandaConector.uploadZipFile"), "E"); Console.WriteLine(ex); return(false); } finally { if (stream != null) { stream.Close(); stream.Dispose(); } } }
/// <summary> /// <para>Begins an asynchronous send to the upload session append route.</para> /// </summary> /// <param name="sessionId">The upload session ID (returned by <see /// cref="Dropbox.Api.Files.Routes.FilesRoutes.UploadSessionStartAsync" />).</param> /// <param name="offset">The amount of data that has been uploaded so far. We use this /// to make sure upload data isn't lost or duplicated in the event of a network /// error.</param> /// <param name="body">The document to upload</param> /// <param name="callback">The method to be called when the asynchronous send is /// completed.</param> /// <param name="callbackState">A user provided object that distinguished this send /// from other send requests.</param> /// <returns>An object that represents the asynchronous send request.</returns> public sys.IAsyncResult BeginUploadSessionAppend(string sessionId, ulong offset, io.Stream body, sys.AsyncCallback callback, object callbackState = null) { var uploadSessionCursor = new UploadSessionCursor(sessionId, offset); return this.BeginUploadSessionAppend(uploadSessionCursor, body, callback, callbackState); }
//private async Task<bool> UploadAsync(string fileBaseEncoded, string fileNameAndLocationPath) //{ // // var dropboxClient = IsAuthenticateUser(); // if (dropboxClient != null) // { // try // { // using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(fileBaseEncoded))) // { // var updated = await dropboxClient.Files.UploadAsync( // fileNameAndLocationPath, // WriteMode.Overwrite.Instance, // body: memoryStream); // } // } // catch (ArgumentException ex) // { // Linetime.Logging.Debugging.DebugLog(ex); // } // } // return false; //} public async Task <string> ChunkUpload(string dropboxFileName, string fileBaseEncoded) { var message = ""; // var dropboxClient = IsAuthenticateUser(); if (dropboxClient != null) { // Chunk size is 128KB. const int chunkSize = 128 * 1024; // Create a random file of 1MB in size. byte[] byteArray = Convert.FromBase64String(fileBaseEncoded); //new Random().NextBytes(fileContent); try { using (var stream = new MemoryStream(byteArray)) { int numChunks = (int)Math.Ceiling((double)stream.Length / chunkSize); byte[] buffer = new byte[chunkSize]; string sessionId = null; for (var idx = 0; idx < numChunks; idx++) { // Console.WriteLine("Start uploading chunk {0}", idx); var byteRead = stream.Read(buffer, 0, chunkSize); using (MemoryStream memStream = new MemoryStream(buffer, 0, byteRead)) { if (idx == 0) { var result = await dropboxClient.Files.UploadSessionStartAsync(body : memStream); sessionId = result.SessionId; } else { UploadSessionCursor cursor = new UploadSessionCursor(sessionId, (ulong)(chunkSize * idx)); if (idx == numChunks - 1) { await dropboxClient.Files.UploadSessionFinishAsync(cursor, new CommitInfo(dropboxFileName), memStream); } else { await dropboxClient.Files.UploadSessionAppendV2Async(cursor, body : memStream); } } } } } } catch (ArgumentException ex) { message = string.Format("Failed: Exception - {0} ", ex.Message); } } return(message); }
/// <summary> /// <para>Begins an asynchronous send to the upload session finish route.</para> /// </summary> /// <param name="cursor">Contains the upload session ID and the offset.</param> /// <param name="commit">Contains the path and other optional modifiers for the /// commit.</param> /// <param name="body">The document to upload</param> /// <param name="callback">The method to be called when the asynchronous send is /// completed.</param> /// <param name="callbackState">A user provided object that distinguished this send /// from other send requests.</param> /// <returns>An object that represents the asynchronous send request.</returns> public sys.IAsyncResult BeginUploadSessionFinish(UploadSessionCursor cursor, CommitInfo commit, io.Stream body, sys.AsyncCallback callback, object callbackState = null) { var uploadSessionFinishArg = new UploadSessionFinishArg(cursor, commit); return this.BeginUploadSessionFinish(uploadSessionFinishArg, body, callback, callbackState); }
public static async Task <FileMetadata> UploadChunked(this DropboxClient client, string folder, string fileName, Stream fs, CancellationToken cancellationToken, IProgress <long> progress, DateTime?modified = default) { int chunks = (int)Math.Ceiling((double)fs.Length / ChunkSize); byte[] buffer = new byte[ChunkSize]; string sessionId = null; FileMetadata resultMetadata = null; var fullDestinationPath = CombinePath(folder, fileName); for (var i = 0; i < chunks; i++) { if (cancellationToken.IsCancellationRequested) { throw new OperationCanceledException(cancellationToken); } var bytesRead = fs.Read(buffer, 0, (int)ChunkSize); using (var memStream = new MemoryStream(buffer, 0, bytesRead)) { if (i == 0) { var result = await client.Files.UploadSessionStartAsync(body : memStream); sessionId = result.SessionId; } else { UploadSessionCursor cursor = new UploadSessionCursor(sessionId, (ulong)(ChunkSize * i)); if (i == chunks - 1) { var commitInfo = new CommitInfo( path: fullDestinationPath, mode: WriteMode.Overwrite.Instance, clientModified: modified ); resultMetadata = await client.Files.UploadSessionFinishAsync(cursor, commitInfo, memStream); if (!cancellationToken.IsCancellationRequested) { progress.Report(fs.Length); } } else { await client.Files.UploadSessionAppendV2Async(cursor, body : memStream); if (!cancellationToken.IsCancellationRequested) { progress.Report(i * ChunkSize); } } } } } return(resultMetadata); }