c# Dropbox RestSharp download file to stream

北战南征 提交于 2019-12-12 04:19:27

问题


I have an 'ASP.NET' console application and I use 'RestSharp' client for Dropbox.

I use this code to download a file :

 var baseUrl = "https://content.dropboxapi.com";

 var client = new RestClient(baseUrl);
 client.Authenticator = OAuth1Authenticator.ForRequestToken(mc_apiKey, mc_appsecret);

 RestRequest request = new RestRequest(string.Format("/{0}/files/auto", mc_version), Method.GET);

 client.Authenticator = OAuth1Authenticator.ForProtectedResource(mc_apiKey, mc_appsecret, accessToken.Token, accessToken.Secret);
 request.AddParameter("path", path);

 var responseAccount = client.Execute(request);
 var fileString = responseAccount.Content;
 byte[] b1 = System.Text.Encoding.UTF8.GetBytes (fileString);

When call client.Execute(request)the whole file is loaded in memory, so when I have a very largefile in Dropbox the program will crash.

I need to get the file to stream without using client.DownloadData(request).SaveAs(path) to download to local storage.

I need to be able to stream the file in chunks.


回答1:


You can set the request.ResponseWriter like so :

  var baseUrl = "https://content.dropboxapi.com";

  var client = new RestClient(baseUrl);
  client.Authenticator = OAuth1Authenticator.ForRequestToken(mc_apiKey,mc_appsecret);

  RestRequest request = new RestRequest(string.Format("/{0}/files/auto", mc_version), Method.GET);

  client.Authenticator = OAuth1Authenticator.ForProtectedResource(mc_apiKey, mc_appsecret, accessToken.Token, accessToken.Secret);
  request.AddParameter("path", path);

  string tempFile = Path.GetTempFileName();
  using(var stream = File.Create(tempFile, 1024, FileOptions.DeleteOnClose ))
  {
    request.ResponseWriter = (responseStream) => responseStream.CopyTo(stream);
    var response = client.DownloadData(request);
  }

You can see the example from the docs here




回答2:


I found the best answer in link:

 string url = String.Format("https://content.dropboxapi.com/1/files/auto{0}?oauth_consumer_key={1}&oauth_token={2}&oauth_signature={3}%26{4}", path, app-key, access-token, app-secret, access-token-secret);
 HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
 webRequest.Method = "Get";
 WebResponse webResponse = null;
  try
  {
     webResponse = webRequest.GetResponse();
     return webResponse.GetResponseStream();
  }
  catch (Exception ex)
  {
    throw ex;       
  }


来源:https://stackoverflow.com/questions/34183238/c-sharp-dropbox-restsharp-download-file-to-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!