[英]How to upload to OneDrive using Microsoft Graph Api in c#
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.我一直在尝试上传到 OneDrive 帐户,但我无可救药地无法上传小于或大于 4MB 的文件。 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 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. Microsoft Graph API 上的此文档对 HTTP 代码非常友好,我相信我能够将文档公平地“翻译”为 C#,但仍然无法获取文件并上传到 OneDrive。 Some places online seem to be using byte arrays?
网上有些地方好像是用字节arrays? Which I am completely unfamiliar with since my primary language is C++ and we just use ifstream/ofstream.
我完全不熟悉,因为我的主要语言是 C++,我们只使用 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).就目前而言,它会在 OneDrive 中上传一个带有波浪号“~”的临时文件(就像我只能打开但不能从文件中导入任何数据一样)。 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.消息:在打开的属性上找到了 function 'microsoft.graph.createUploadSession'。 Functions on open properties are not supported.
不支持打开属性的函数。
Thanks, any comments and help would mean a lot.谢谢,任何评论和帮助都意义重大。
Try this approach with memory stream and PutAsync<DriveItem>
request:使用 memory stream 和
PutAsync<DriveItem>
请求尝试此方法:
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.我假设您已经授予 Microsoft Graph Files.ReadWrite.All权限。 Check your API permission .
检查您的API 权限。 I tested this code snippet with pretty old Microsoft.Graph library version 1.21.0.
我用相当旧的 Microsoft.Graph 库版本 1.21.0 测试了这个代码片段。 Hopefully it will work for you too.
希望它也对你有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.