尝试使用.NET SDK for Microsoft Graph上传文件。这是代码:
DriveItem file = new DriveItem()
{
File = new Microsoft.Graph.File(),
Name = filename,
ParentReference = new ItemReference()
{
DriveId = parent.ParentReference.DriveId,
Path = path + "/" + filename
}
};
var freq = _client
.Me
.Drive
.Items[parent.Id]
.Children
.Request();
// add the drive item
file = await freq.AddAsync(file);
DriveItem uploadedFile = null;
using (MemoryStream stream = new MemoryStream(data))
{
var req = _client
.Me
.ItemWithPath(path + "/" + file.Name)
.Content
.Request();
stream.Position = 0;
// upload the content to the driveitem just created
try
{
uploadedFile = await req.PutAsync<DriveItem>(stream);
}
catch(Exception ex)
{
Debug.WriteLine("File Put Error"); <<< FAILS HERE
}
}
return uploadedFile;
在req.PutAsync方法上抛出异常以上载包含文件内容的字节数组。我只是测试一个简单的文本文件,大小不到100个字节。该异常包含错误请求和不支持的段类型。
该文件在OneDrive中创建,但包含0个字节。
答案 0 :(得分:3)
Me.ItemWithPath()需要/ me之后的完整路径。例如,_client.Me.ItemWithPath(“/ drives / driveId / items / itemId:/ file / path”)。这个方法是通过API返回的ItemReference上返回的Path可以传递给ItemWithPath方法而无需任何处理。
您想要使用的是:
var req = _client
.Me
.Drive
.ItemWithPath(path + "/" + file.Name)
.Content
.Request();
或:
var req = _client
.Me
.ItemWithPath(file.ParentReference.Path + "/" + file.Name)
.Content
.Request();
答案 1 :(得分:1)
我发现有时更容易跳过在SDK语句中设置包含文件夹ID的路径...在OneDrive和统一组中工作..
import * as datasvc from "services/datasvc"
我真的希望能够像这样设置驱动器ID和文件夹ID:
var createdFile = await graphClient.Me.Drive
.Items[currentDriveFolder.id]
.ItemWithPath(fileName)
.Content.Request()
.PutAsync<DriveItem>(stream);