2017-02-07 41 views
0

我想使用访问令牌将压缩文件上传到Dropbox。下面的代码适用于解压文件使用C上传压缩文件到Dropbox使用C#

private static async Task FileUploadToDropbox(string filePath, string fileName, byte[] fileContent) 
{ 
    var client = new DropboxClient("Access Token"); 

    const int chunkSize = 1024; 

    using (var stream = new MemoryStream(fileContent)) 
    { 
     int numChunks = (int)Math.Ceiling((double)stream.Length/chunkSize); 

     byte[] buffer = new byte[chunkSize]; 
     string sessionId = null; 

     for (var idx = 0; idx < numChunks; idx++) 
     { 
      var byteRead = stream.Read(buffer, 0, chunkSize); 

      using (MemoryStream memStream = new MemoryStream(buffer, 0, byteRead)) 
      { 
       if (idx == 0) 
       { 
        var result = await client.Files.UploadSessionStartAsync(body: memStream); 
        sessionId = result.SessionId; 
       } 

       else 
       { 
        UploadSessionCursor cursor = new UploadSessionCursor(sessionId, (ulong)(chunkSize * idx)); 

        if (idx == numChunks - 1) 
        { 
         await client.Files.UploadSessionFinishAsync(cursor, new CommitInfo(filePath + "/" + fileName), memStream); 
        } 

        else 
        { 
         await client.Files.UploadSessionAppendV2Async(cursor, body: memStream); 
        } 
       } 
      } 
     } 
    } 
} 

但是当我尝试使用此代码上传一个压缩文件,它上传一个空的压缩文件到Dropbox的。我正在读取压缩文件作为字节数组并将其传递给上述方法。虽然文件大小保持不变,但当我下载文件并尝试提取文件时,它说压缩文件是空的。

回答

0
private static async Task FileUploadToDropbox(string filePath, string fileName, string fileSource) 
     { 
      using (var dbx = new DropboxClient("access Token")) 
      using (var fs = new FileStream(fileSource, FileMode.Open, FileAccess.Read)) 
      { 
       var updated = await dbx.Files.UploadAsync(
        (filePath + "/" + fileName), WriteMode.Overwrite.Instance, body: fs); 
      } 
     } 

以上方法为我工作。

0

请试试这个:

/// <summary> 
    /// Function to import local file to dropbox. 
    /// </summary> 
    public static async Task<bool> WriteFileToDropBox() 
    { 
     try 
     { 
      //Connecting with dropbox. 
      var file = "File path at dropbox"; 
      using (var dbx = new DropboxClient("Access Token")) 
      using (var fs = new FileStream("Path of file to be uploaded.") 
      { 
       var updated = await dbx.Files.UploadAsync(file, WriteMode.Add.Instance, body: fs); 
      } 
      return true; 
     } 
     catch (Exception err) 
     { 
      MessageBox.Show(err.Message); 
      return false; 
     } 
    } 
+0

@Akshay,如果您觉得有用,请将其标记为答案,以便它也能帮助其他人。 –

+0

我收到一个异常:“流不支持阅读。”使用你的代码。 – Akshay