How to upload to OneDrive using Microsoft Graph Api in c#

十年热恋 提交于 2020-07-10 08:25:08

问题


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:


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.



来源:https://stackoverflow.com/questions/61264546/how-to-upload-to-onedrive-using-microsoft-graph-api-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!