Search code examples
c#sharepointmicrosoft-graph-api

Item not found on sharepoint


I'm using graph api and running a for loop through a list of items, I then try to update the item and I keep getting a response telling me that the item was not found. The permissions say I should be able to view it and the because the names matched I'm thinking it should all work.

              var drives = await graphClient.Drives.GetAsync();
              var rootDrive = drives.Value[0];
              var items = await graphClient.Drives[rootDrive.Id].List.Items.GetAsync();
              foreach (var item in items.Value)
              {
                  if (item.Name == fileName || item.WebUrl.Contains(fileName))
                  {
                      var requestBody = new DriveItem
                      {
                          Content = fileBytes, 
                      };
                      var result = await graphClient.Drives[rootDrive.Id].Items[item.Id].PatchAsync(requestBody); //returns itemnotfound
                  }
              }

enter image description here


Solution

  • The item is ListItem and you want to update DriveItem, so you need id of driveItem.

    When retrieving items, expand driveItem and return only driveItem's id and name.

    When calling patch, use id of driveItem

    var drives = await graphClient.Drives.GetAsync();
    var rootDrive = drives.Value[0];
    var items = await graphClient.Drives[rootDrive.Id].List.Items.GetAsync((rc) =>
    {
        rc.QueryParameters.Expand = new string []{ "driveItem($select=id,name)" };
    });
    foreach (var item in items.Value)
    {
        if (item.driveItem.Name == fileName || item.Name == fileName || item.WebUrl.Contains(fileName))
        {
            var requestBody = new DriveItem
            {
                Content = fileBytes, 
            };
            var result = await graphClient.Drives[rootDrive.Id].Items[item.DriveItem.Id].PatchAsync(requestBody);
        }
    }