我正在使用适用于 .NET 的新 Dropbox SDK v2。
我正在尝试将文档上传到 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);
}
}
此代码片段实际上在 Dropbox 帐户上创建了一个带有“Testing!”的 test.txt 文档。内容,但我想上传具有给定路径(例如:“C:\MyDocuments\test.txt”)的文档,这可能吗?
非常感谢任何帮助。
最佳答案
UploadAsync
方法将使用您传递给 body
参数的任何数据作为上传的文件内容。
如果您想上传本地文件的内容,您需要为其提供该文件的流。
这里有一个例子展示了如何使用此方法上传本地文件(包括处理大文件的逻辑):
此示例使用 Dropbox .NET library将文件上传到 Dropbox 帐户,使用较大文件的上传 session :
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);
}
}
}
}
}
关于c# - 文件上传 Dropbox v2.0 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40970095/