DropBox API调用上传零字节文件

时间:2018-06-06 17:41:19

标签: c# rest api dropbox

我正在尝试使用rest调用将文件上传到dropbox,但它没有上传实际文件,而是上传了一个零字节文件。

如果我错过了什么,请检查代码并告诉我。

var task = Task.Run((Func<Task<int>>)OrderExtractUsecase.DropBox);
task.Wait();
int x = task.Result;

Dropbox任务代码是:

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;
        }
    }

上传任务代码是:

    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;
    }

1 个答案:

答案 0 :(得分:1)

如上所述awh112,您需要重置memoryStream的位置。在copyTo之后,Position memoryStream是文件的长度。因此,您的代码将上传一个零字节文件。我已经通过以下方式证实了这一点:

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);

打印:(在我的情况下,我的测试文件只有12个字节)

12
0

您可以像这样回放:

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);

打印:

12
0
12

然后,生成的上传文件包含预期内容。