Search code examples
c#sharepointmicrosoft-teamsonedrivemicrosoft-graph-sdks

Get the Sharepoint site for a Group and upload a file using Graph


Using the MS Graph SDK via a Teams application, I'm trying to get the Sharepoint site of a group and upload a file to it. I'm unable to get a reference to the Drive of the site, it is always null for me. Here is what I'm trying:

var siteName = "testSite";
var site = (await graphService.Groups[groupId].Sites.Request().GetAsync())
    .FirstOrDefault(x => x.DisplayName == SiteName);   

using var wc = new WebClient();
using var stream = new MemoryStream(wc.DownloadData(attachment.DownloadUrl));
// site.Drive is always null
var uploadedFile = await site.Drive.Root
    .ItemWithPath($"Test/123/file.jpg").Content.Request().PutAsync<DriveItem>(stream);  

The application has Files.ReadWrite.All, Group.Read.All and Sites.ReadWrite.All permissions.

Using Postman, I get the following when making a call for groups/{{id}}/site/root, using the same token (the hidden values are all correct)

Postman cal


Solution

  • You could try to use the below way to upload file for a group site:

       var item = await graphClient.Groups[groupId].Drive.Root
                   .ItemWithPath("test.docx")
                   .Content
                   .Request()
                   .PutAsync<DriveItem>(stream);