Reputation: 43
I am trying to upload a file to dropbox using rest calls but it is not uploading the actual file, it is uploading a zero byte file.
Please check the code and let me know if i am missing something.
var task = Task.Run((Func<Task<int>>)OrderExtractUsecase.DropBox);
task.Wait();
int x = task.Result;
Dropbox task Code is:
static async Task<int> DropBox()
{
try
{
Dropbox_Utility objDropBox = new Dropbox_Utility("<accessid>");
foreach (string temp in fileList)
{
await objDropBox.Upload("/Assist", temp);
}
return 1;
}
catch(Exception ex)
{
return -1;
}
}
Upload task code is:
public async Task<string> Upload(string folder, string filefullpath)
{
string filename = string.Empty;
string fileID = string.Empty;
try
{
filename = Path.GetFileName(filefullpath);
using (FileStream fileStream = File.OpenRead(filefullpath))
{
using (MemoryStream memoryStream = new MemoryStream())
{
fileStream.CopyTo(memoryStream);
var response = await dbx.Files.UploadAsync(folder + "/" + filename, WriteMode.Overwrite.Instance, body: memoryStream);
fileID = response.Id;
}
}
}
catch (Exception ex) { throw; }
finally { }
return fileID;
}
Upvotes: 0
Views: 508
Reputation: 16940
As awh112 mentioned, you need to reset the position of memoryStream
. After the copyTo
, the Position
of memoryStream
is the length of the file. For that reason, your code will upload a zero byte file. I've confirmed as much with the following:
fileStream.CopyTo(memoryStream);
Console.WriteLine(memoryStream.Position);
var response = await dbx.Files.UploadAsync(folder + "/" + filename, WriteMode.Overwrite.Instance, body: memoryStream);
Console.WriteLine((response as FileMetadata).Size);
That prints: (in my case, my test file is just 12 bytes long)
12
0
You can rewind it like this:
fileStream.CopyTo(memoryStream);
Console.WriteLine(memoryStream.Position);
memoryStream.Position = 0;
Console.WriteLine(memoryStream.Position);
var response = await dbx.Files.UploadAsync(folder + "/" + filename, WriteMode.Overwrite.Instance, body: memoryStream);
Console.WriteLine((response as FileMetadata).Size);
That prints:
12
0
12
The resulting uploaded file then contains the expected contents.
Upvotes: 1