Sharepoint PnP read list of items C#

Viewed 34

This is a PnP.Pwershell command

(Get-PnPListItem -List Content -Fields "Title","ctmImage","ctmAbstract","ctmActive","ctmContent","ctmCategory").FieldValues

I am using Microsoft.SharePoint.Client and PnP.Framework assembly and writing a console app and using app only auth access with client id and client secret

How do I write the above command in C#? I am trying to read the list items

2 Answers

You can try something like this. Well it is mostly pure SharePoint Client api, but I am not sure what exactly is part of the PnP.Framework. I only used the AuthenticationManager to get a token. A good guide for setting up the permissions you can find here: https://github.com/pnp/pnpframework/blob/dev/docs/MigratingFromPnPSitesCore.md

var web = context.Web;
var sharePointList = web.GetListByTitle("Test");
var items = sharePointList.GetItems(CamlQuery.CreateAllItemsQuery());

context.Load(items, i => i.Include(i => i["Title"], i=> i["Created"]));
await context.ExecuteQueryAsync();

foreach(var item in items) 
{
    foreach(var key in item.FieldValues.Keys) {
        Console.WriteLine($"{key}: {item.FieldValues[key]}");
    }
}

Depending on the number of items in the list, this might not be the best way. You could create a custom CAML Query and use it in the GetItems call. Some more usefull extensions you might find in the PnP Core SDK: https://pnp.github.io/pnpcore/ (for querying list items see here https://pnp.github.io/pnpcore/using-the-sdk/listitems-intro.html). Maybe, if you can, you should drop the PnP.Framework and continue with the PnP Core SDK.

I will recommend you to use CSOM to read list items.You can refer to the following code

using (ClientContext clientContext = new ClientContext("http://xxx.sharepoint.com/sites/MySite"))
{
List targetList = clientContext.Web.Lists.GetByTitle("Content");

CamlQuery oQuery = CamlQuery.CreateAllItemsQuery();
 
ListItemCollection oCollection = targetList.GetItems(oQuery);
clientContext.Load(oCollection);
clientContext.ExecuteQuery();
 
foreach (ListItem oItem in oCollection)
{
Console.WriteLine(oItem["Title"].ToString());
Console.WriteLine(oItem["ctmImage"].ToString());
Console.WriteLine(oItem["ctmAbstract"].ToString());
Console.WriteLine(oItem["ctmActive"].ToString());
Console.WriteLine(oItem["ctmContent"].ToString());
Console.WriteLine(oItem["ctmCategory"].ToString());
}
}
Related