首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Microsoft Graph API C# SDK将文件上传到SharePoint库文件夹?

如何使用Microsoft Graph API C# SDK将文件上传到SharePoint库文件夹?
EN

Stack Overflow用户
提问于 2021-08-11 09:14:00
回答 1查看 209关注 0票数 0

我找不到任何关于如何使用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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-08-11 09:14:00

这就是我最后是如何做到的:

代码语言:javascript
复制
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对象检索驱动器。

代码语言:javascript
复制
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;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68739183

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档