将文件上传到 Sharepoint 在线图书馆

Mat*_*hew 1 c# asp.net azure sharepoint-online microsoft-graph-api

我正在尝试使用 C# 图形 sdk 将文件上传到 Sharepoint Online 文档库,但未能成功。

我可以获取驱动器/库,但是如果我将它作为驱动器获取,则 Root 为空,并且出现异常。如果我将其作为列表处理,则似乎无法使用 CreateUploadSession 方法。

以列表形式获取文档库有效:

await graphClient.Sites[SPUrl + ":"].Sites[SpPath + ":"].Lists[libId].Request().GetAsync();
Run Code Online (Sandbox Code Playgroud)

通过驱动器 ID 获取文档库作为驱动器似乎不起作用:

var drive = await graphClient.Sites[SPUrl + ":"].Sites[SpPath + ":"].Drives[driveId].Request().GetAsync();
Run Code Online (Sandbox Code Playgroud)

将文档库作为其列表的驱动器执行以下操作:

var drive = await graphClient.Sites[SPUrl + ":"].Sites[SpPath + ":"].Lists[libId].Drive.Request().GetAsync();
Run Code Online (Sandbox Code Playgroud)

但是尝试获取该驱动器的根目录会导致“错误请求:指定的 URL 无效”。尝试 Drive.Items.Request() 也是如此。但据我所知,我需要有驱动器的根来做到这一点:

var uploadSession = await graphClient.Sites[SPUrl + ":"].Sites[SpPath + ":"].Lists[libId].Drive.Root.ItemWithPath(file.FileName).CreateUploadSession().Request().PostAsync();
Run Code Online (Sandbox Code Playgroud)

但是我有三个文档库,它们都将 Root 显示为空。显然我错过了一些东西,但我不清楚是什么。

Vad*_*hev 5

实际上,如果站点是由服务器相对 URL 寻址的,则以下查询

GET https://graph.microsoft.com/v1.0/sites/{hostname}:/{server-relative-path}:/drive
Run Code Online (Sandbox Code Playgroud)

成功并返回默认驱动器,而以下内容:

GET https://graph.microsoft.com/v1.0/sites/{hostname}:/{server-relative-path}:/drive/root
Run Code Online (Sandbox Code Playgroud)

失败并返回错误 Url specified is invalid.

这似乎是Microsoft Graph 本身的错误。无论如何,可以考虑使用以下选项将文件上传到库中。

假定siteUrl对应于站点服务器相对 url 和 listId库唯一标识符

它由以下步骤组成:

  • 通过服务器相对 url 解析站点
  • 访问库的根文件夹
  • 上传一个文件

例子

//1.resolve site by server relative url
var targetSite = await graphClient.Sites.GetByPath(siteUrl,hostName).Request().GetAsync();    //2.access root folder for for a Library
var targetFolder = graphClient.Sites[targetSite.Id]
       .Lists[listId]
       .Drive
       .Root;

 //3.Upload a file
 var pathToFile = @"c:\Temp\Guide.docx";
 using (var fileStream = new FileStream(pathToFile, FileMode.Open, FileAccess.Read))
 {
      var uploadedItem = await targetFolder
        .ItemWithPath("Guide.docx")
        .Content
        .Request()
        .PutAsync<DriveItem>(fileStream);
 }
Run Code Online (Sandbox Code Playgroud)

在哪里

  • hostName是网站集主机名(例如 contoso.sharepoint.com
  • siteUrl - 服务器相对站点 url,例如 /sites/management