4

I have been trying to upload to a OneDrive account and I am hopelessly stuck not being able to upload neither less or greater than 4MB files. I have no issues accessing the drive at all, since I have working functions that create a folder, rename files/folders, and a delete files/folders.

https://learn.microsoft.com/en-us/graph/api/driveitem-put-content?view=graph-rest-1.0&tabs=csharp

This documentation on Microsoft Graph API is very friendly to HTTP code, and I believe I am able to fairly "translate" the documentation to C#, but still fail to grab a file and upload to OneDrive. Some places online seem to be using byte arrays? Which I am completely unfamiliar with since my primary language is C++ and we just use ifstream/ofstream. Anyways, here is the portion of code in specific (I hope this is enough):

var item = await _client.Users[userID].Drive.Items[FolderID]//"01YZM7SMVOQ7YVNBXPZFFKNQAU5OB3XA3K"].Content
                    .ItemWithPath("LessThan4MB.txt")//"D:\\LessThan4MB.txt")
                    .CreateUploadSession()
                    .Request()
                    .PostAsync();
            Console.WriteLine("done printing");

As it stands, it uploads a temporary file that has a tilde "~" in the OneDrive (like as if I was only able to open but not import any data from the file onto it). If I swap the name of the file so it includes the file location it throws an error:

Message: Found a function 'microsoft.graph.createUploadSession' on an open property. Functions on open properties are not supported.

Kiquenet
  • 14,494
  • 35
  • 148
  • 243

1 Answers1

5

Try this approach with memory stream and PutAsync<DriveItem> request:

string path = "D:\\LessThan4MB.txt";
byte[] data = System.IO.File.ReadAllBytes(path);

using (Stream stream = new MemoryStream(data))
{
    var item = await _client.Me.Drive.Items[FolderID]
            .ItemWithPath("LessThan4MB.txt")
            .Content
            .Request()
            .PutAsync<DriveItem>(stream);
}

I am assuming you have already granted Microsoft Graph Files.ReadWrite.All permission. Check your API permission. I tested this code snippet with pretty old Microsoft.Graph library version 1.21.0. Hopefully it will work for you too.

Tomas Paul
  • 490
  • 5
  • 13
  • Thanks a lot mate, this was exactly what I needed, I just don't understand byte arrays and whatnot, but I'll figure it out now that I see how this works. I will be currently figuring out how to upload files larger than 4MB! – MICHELRODRIGUEZ1 Apr 17 '20 at 09:49
  • Why not use only the method greater than 4mb? Is it that much slower than this single request option? – Irish Redneck Dec 03 '22 at 12:19