Search code examples
c#sharepointmicrosoft-graph-apisharepoint-onlinecaml

Retrieve SharePoint document ID using CAML query


I'm using the following code to retrieve a list of documents and folders from SharePoint Online:

Web web = sp.Web;

string spdocumenturl = "/sites/MySite/Shared%20Documents/My%20Site%20Documents/MyFolder";

Microsoft.SharePoint.Client.List documentlist = web.Lists.GetByTitle("Documents");
CamlQuery query = new CamlQuery();
query.FolderServerRelativeUrl = spdocumenturl;
query.ViewXml = "<View Scope='RecursiveAll'><RowLimit>5000</RowLimit></View>";
ListItemCollection listItems = documentlist.GetItems(query);

sp.Load(listItems);
sp.ExecuteQuery();

The code works to retrieve all of the files/folders I'm looking for but I'm not sure how to get the ID of the file. There's a property called ID but it's a really small number (like 3, for example) so that's not right. There's also a property called UniqueId but that doesn't match what Microsoft Graph says the ID is.

My end goal is to store the IDs and use them later by another app that retrieves the document content from the Microsoft Graph API based on the ID so it has to match.

Can someone tell me how to retrieve the document ID with my results? Thanks!


Solution

  • The ID you mentioned is listItemId and it can be used when calling the Graph API.

    The listItem can have a relationship to driveItem which represents a file, folder, or other item stored in a drive.

    You should be able to specify a relative URL to access list item.

    GET https://graph.microsoft.com/v1.0/sites/<tenant_name>.sharepoint.com:/sites/{site_name}:/lists/{list_title}/items/{list_item_id}/driveItem
    

    Based on your example site_name is MySite, list_title is Documents

    GET https://graph.microsoft.com/v1.0/sites/tenant.sharepoint.com:/sites/MySite:/lists/Documents/items/3/driveItem