文件上传Dropbox v2.0 API

use*_*165 3 c# dropbox dropbox-api

我正在使用新的Dropbox SDK v2 for .NET.

我正在尝试将文档上传到Dropbox帐户.

public async Task UploadDoc()
    {
        using (var dbx = new DropboxClient("XXXXXXXXXX"))
        {
            var full = await dbx.Users.GetCurrentAccountAsync();
            await Upload(dbx, @"/MyApp/test", "test.txt","Testing!");
        }
    }
async Task Upload(DropboxClient dbx, string folder, string file, string content)
    {
        using (var mem = new MemoryStream(Encoding.UTF8.GetBytes(content)))
        {
            var updated = await dbx.Files.UploadAsync(
                folder + "/" + file,
                WriteMode.Overwrite.Instance,
                body: mem);

            Console.WriteLine("Saved {0}/{1} rev {2}", folder, file, updated.Rev);
        }
    }
Run Code Online (Sandbox Code Playgroud)

此代码段实际上在Dropbox帐户上创建了一个test.txt文档,其中包含"Testing!" 内容,但我想上传一个带有给定路径文档(例如:"C:\ MyDocuments\test.txt"),这可能吗?

任何帮助将非常感谢.

Gre*_*reg 6

UploadAsync方法将使用您传递给body参数的任何数据作为上载的文件内容.

如果要上载本地文件的内容,则需要为该文件提供一个流.

这里有一个示例,说明如何使用此方法上传本地文件(包括处理大文件的逻辑):

此示例使用Dropbox .NET库将文件上载到Dropbox帐户,使用较大文件的上传会话:

private async Task Upload(string localPath, string remotePath)
{
    const int ChunkSize = 4096 * 1024;
    using (var fileStream = File.Open(localPath, FileMode.Open))
    {
        if (fileStream.Length <= ChunkSize)
        {
            await this.client.Files.UploadAsync(remotePath, body: fileStream);
        }
        else
        {
            await this.ChunkUpload(remotePath, fileStream, (int)ChunkSize);
        }
    }
}

private async Task ChunkUpload(String path, FileStream stream, int chunkSize)
{
    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 this.client.Files.UploadSessionStartAsync(false, memStream);
                sessionId = result.SessionId;
            }
            else
            {
                var cursor = new UploadSessionCursor(sessionId, (ulong)chunkSize * idx);

                if (idx == numChunks - 1)
                {
                    FileMetadata fileMetadata = await this.client.Files.UploadSessionFinishAsync(cursor, new CommitInfo(path), memStream);
                    Console.WriteLine (fileMetadata.PathDisplay);
                }
                else
                {
                    await this.client.Files.UploadSessionAppendV2Async(cursor, false, memStream);
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)