使用DropBox SDK C#使用UploadSessionStartAsync覆盖现有文件

时间:2018-07-06 10:50:27

标签: c# dropbox dropbox-sdk

必须在Dropbox上上传大型文件。我也想实施进度条并上传。到处都提到我应该使用UploadSessionStartAsync。 我不知道如何使用UploadSessionStartAsync覆盖现有文件(如果已经存在)。我可以先删除文件,然后进行新的上载,但效果很好,但是由于先前文件的filemetadata随后丢失,因此无法执行。使用UploadAsync很容易,因为已经有一个WriteMode.Overwrite参数! 这是我的代码:

/// <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);
                            }
                        }
                    }
                }
            }
        }

1 个答案:

答案 0 :(得分:2)

the Dropbox API v2 .NET SDK中使用上载会话时,可以在传递给WriteModeCommitInfo中设置UploadSessionFinishAsync

它看起来像这样:

await client.Files.UploadSessionFinishAsync(cursor, new CommitInfo(folder + "/" + fileName, mode:WriteMode.Overwrite.Instance), memStream);