0

I am trying to download a file from my onedrive using the microsoft graph api. I have managed to get to the point where i can retrieve the item from the GraphServiceClient. However, once i get the file using /me/Drive/Items/{itemid}/Content it returns to me a System.IO.Stream object.

How do i use this System.IO.Stream object to download the file?

Here is the code i have now for getting the file (for security purposes i did not put the itemid in the sample code, but i can assure you it is correct.) :

public async Task<ActionResult> OneDriveDownload()
{
    string token = await GetAccessToken();
    if (string.IsNullOrEmpty(token))
    {
        // If there's no token in the session, redirect to Home
        return Redirect("/");
    }

    GraphServiceClient client = new GraphServiceClient(
        new DelegateAuthenticationProvider(
            (requestMessage) =>
            {
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

                return Task.FromResult(0);
            }));

    try
    {
        var stream = await client.Me.Drive.Items[ItemID].Content.Request().GetAsync();
        return View(stream);
    }
    catch (ServiceException ex)
    {
        return RedirectToAction("Error", "Home", new { message = "ERROR retrieving messages", debug = ex.Message });
    }
}

Additionally, i would like to create a button that can execute this download in the view.

dtlvd
  • 457
  • 1
  • 8
  • 21
Azuraith
  • 1,030
  • 14
  • 28
  • Yea i looked at the before posting this. Doesn't really explain how to download the file to my pc... – Azuraith Apr 13 '18 at 12:52
  • 1
    Here's a one-liner, seeing as you're struggling to understand the duplicate : `using(var fs=File.OpenWrite(somePath)){stream.CopyTo(fs);}` – spender Apr 13 '18 at 12:55
  • 1
    ...or in async world: `using(var fs=File.OpenWrite(somePath)){await stream.CopyToAsync(fs);}` – spender Apr 13 '18 at 12:58
  • I used the solution from this other question to solve my problem. Thanks for your help everyone. https://stackoverflow.com/questions/5002834/saving-a-file-from-stream-to-disk-using-c-sharp – Azuraith Apr 13 '18 at 13:38
  • 1
    If it's the [top-voted and selected answer](https://stackoverflow.com/a/5002881/14357) to the question you linked to, think twice before using the code. It's dangerously broken. See the comments that I have left below to understand why. – spender Apr 13 '18 at 15:58
  • Ok, what would you do instead that i can EASILY replace this with... this was the only method i managed to get actually working because its very simple. – Azuraith Apr 13 '18 at 17:51

0 Answers0