2
votes

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://docs.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.

Thanks, any comments and help would mean a lot.

1

1 Answers

2
votes

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.