我正在使用新的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);
}
}
此代码段实际上在Dropbox帐户上创建了一个test.txt文档,其中包含“Testing!”内容,但我想上传一个带有路径的文档(例如:“C:\ MyDocuments \ test.txt”),这可能吗?
非常感谢任何帮助。
答案 0 :(得分:6)
UploadAsync
方法将使用您传递给body
参数的任何数据作为上传的文件内容。
如果要上传本地文件的内容,则需要为该文件提供一个流。
这里有一个示例,说明如何使用此方法上传本地文件(包括处理大文件的逻辑):
此示例使用Dropbox .NET library将文件上传到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);
}
}
}
}
}
答案 1 :(得分:0)
如果您只想上传具有给定路径的文件,则可以使用以下方法:
private async Task Upload(DropboxClient dbx, string folder, string file, string fileToUpload)
{
using (var mem = new MemoryStream(File.ReadAllBytes(fileToUpload)))
{
var updated = await dbx.Files.UploadAsync(
folder + "/" + file,
WriteMode.Overwrite.Instance,
body: mem);
Console.WriteLine("Saved {0}/{1} rev {2}", folder, file, updated.Rev);
}
}
参数示例:
folder = "/YourDropboxFolderName";
file = "fileName.pdf";
fileToUpload = @"C:\Users\YourUserName\fileName.pdf";