I\'m using the new Dropbox SDK v2 for .NET.
I\'m trying to upload a document to a Dropbox account.
public async Task UploadDoc()
{
using
You can use the following method if you just want to upload a file with a given path:
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);
}
}
Parameter example:
folder = "/YourDropboxFolderName";
file = "fileName.pdf";
fileToUpload = @"C:\Users\YourUserName\fileName.pdf";
The UploadAsync method will use whatever data you pass to the body
parameter as the uploaded file content.
If you want to upload the contents of a local file, you'll need to give it a stream for that file.
There's an example here that shows how to use this method to upload a local file (including logic for handling large files):
This example uses the Dropbox .NET library to upload a file to a Dropbox account, using upload sessions for larger files:
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);
}
}
}
}
}