Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload new file to onedrive using microsoft graph c# asp.net

Trying to upload a file to onedrive that does not already exist. I have managed to get it to update an existing file. But can't seem to figure out how to create a brand new file. I have done this useing the Microsoft.Graph library.

Here is the code that works to update an existing file:

public async Task<ActionResult> OneDriveUpload()
    {
        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
        {
            string path = @"C:/Users/user/Desktop/testUpload.xlsx";
            byte[] data = System.IO.File.ReadAllBytes(path);
            Stream stream = new MemoryStream(data);
            // Line that updates the existing file             
            await client.Me.Drive.Items["55BBAC51A4E4017D!104"].Content.Request().PutAsync<DriveItem>(stream);

            return View("Index");
        }
        catch (ServiceException ex)
        {
            return RedirectToAction("Error", "Home", new { message = "ERROR retrieving messages", debug = ex.Message });
        }
    }
like image 640
Azuraith Avatar asked Apr 13 '18 18:04

Azuraith


1 Answers

I'd suggest using the ChunkedUploadProvider utility that is included in the SDK. Aside from being a little easier to work with, it will allow you to upload files of any side rather than being limited to files under 4MB.

You can find a sample of how to use ChunkedUploadProvider in the OneDriveUploadLargeFile unit test.

To answer your direct question, uploading works the same for both replacing and creating files. You do however need to specify the file name rather than just an existing Item number:

await graphClient.Me
    .Drive
    .Root
    .ItemWithPath("fileName")
    .Content
    .Request()
    .PutAsync<DriveItem>(stream);
like image 170
Marc LaFleur Avatar answered Nov 09 '22 12:11

Marc LaFleur