我找不到任何关于如何使用MS Graph SDK将文件上传到SharePoint库子文件夹的示例。
这些帖子展示了如何使用REST API,而不是C# SDK来做这件事。
upload files in a folder in Sharepoint/OneDrive library using graph api
How to perform a resumable Upload to a SharePoint Site (Not Root) Subfolder using MS Graph API
发布于 2021-08-11 09:14:00
这就是我最后是如何做到的:
try
{
using var stream = new MemoryStream(contentBytes);
// Retrieve the folder item.
var items = await this._graphClient.Sites["siteId"].Lists["listId"].Items
.Request()
.GetAsync();
// I happened to know the folder name in advance, so that is what I used to retrieve the folder item from Items collection.
// I could not find how to query the Graph to get just the folder instead of all the items. Hopefully I will find it and update the code.
var folderItem = items.FirstOrDefault(i => i.WebUrl.Contains($"{path}") && i.ContentType.Name == "Folder");
// you must create a DriveItem, not a ListItem object. It is important to set the the File property.
var listItem = new DriveItem
{
Name = fileName,
File = new Microsoft.Graph.File(),
AdditionalData = new Dictionary<string, object>()
{
{ "@microsoft.graph.conflictBehavior", "replace" }
},
};
listItem = await this._graphClient.Sites["siteId"].Lists["listId"].Items[folderItem.Id].DriveItem.Children
.Request()
.AddAsync(listItem);
// I needed the drive Id here. it is in the Drives properties of the site. It corresponds to the drive associated to the library.
var uploadSession = await this._graphClient.Sites["siteId"].Drives["driveId"]
.Items[listItem.Id]
.CreateUploadSession()
.Request()
.PostAsync();
var largeFileUploadTask = new LargeFileUploadTask<DriveItem>(uploadSession, stream);
UploadResult<DriveItem> uploadResult = await largeFileUploadTask.UploadAsync();
return uploadResult;
}
catch (ServiceException e)
{
Log.Error(e);
throw;
}重要的是要知道,在创建上载会话时,首先需要检索与存储库关联的驱动器ID。如果您加载扩展驱动器查询选项,则可以从site对象检索驱动器。
var siteQueryOptions = new List<QueryOption>()
{
new QueryOption("expand", "drives")
};
var site = await this._graphClient.Sites.GetByPath(siteRelativeUrl, hostName)
.Request(siteQueryOptions)
.GetAsync();
string driveId = site.Drives.FirstOrDefault(d => d.WebUrl.EndsWith(workingDocumentsLibName, StringComparison.InvariantCultureIgnoreCase))?.Id;https://stackoverflow.com/questions/68739183
复制相似问题