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.

6
  • Yea i looked at the before posting this. Doesn't really explain how to download the file to my pc... Commented Apr 13, 2018 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);} Commented Apr 13, 2018 at 12:55
  • 1
    ...or in async world: using(var fs=File.OpenWrite(somePath)){await stream.CopyToAsync(fs);} Commented Apr 13, 2018 at 12:58
  • I used the solution from this other question to solve my problem. Thanks for your help everyone. stackoverflow.com/questions/5002834/… Commented Apr 13, 2018 at 13:38
  • 1
    If it's the top-voted and selected answer 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. Commented Apr 13, 2018 at 15:58

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.