使用应用仅授权,如何将指定PnP PowerShell列表读取命令转为C#代码?
将PnP PowerShell列表项读取命令转换为C#代码(仅应用身份验证)
原PnP PowerShell命令
(Get-PnPListItem -List Content -Fields "Title","ctmImage","ctmAbstract","ctmActive","ctmContent","ctmCategory").FieldValues
对应的C#实现代码
以下是基于Microsoft.SharePoint.Client和PnP.Framework的仅应用身份验证版本,完全匹配PowerShell命令的功能:
using Microsoft.SharePoint.Client; using PnP.Framework; using System; using System.Linq; namespace SharePointListReader { class Program { static void Main(string[] args) { // 替换为你的实际配置 string siteUrl = "https://yourtenant.sharepoint.com/sites/yoursite"; string clientId = "your-client-id-guid"; string clientSecret = "your-client-secret"; // 建立仅应用身份验证的上下文 using (var context = new AuthenticationManager().GetACSAppOnlyContext(siteUrl, clientId, clientSecret)) { try { // 获取目标列表 List contentList = context.Web.Lists.GetByTitle("Content"); context.Load(contentList); context.ExecuteQuery(); // 定义需要加载的字段,和PowerShell的-Fields参数对应 string[] targetFields = { "Title", "ctmImage", "ctmAbstract", "ctmActive", "ctmContent", "ctmCategory" }; // 查询所有列表项(如需筛选可修改CamlQuery) CamlQuery query = CamlQuery.CreateAllItemsQuery(); ListItemCollection items = contentList.GetItems(query); // 明确加载指定字段和FieldValues集合 context.Load(items, itemsCol => itemsCol.Include( item => item.FieldValues, item => item["Title"], item => item["ctmImage"], item => item["ctmAbstract"], item => item["ctmActive"], item => item["ctmContent"], item => item["ctmCategory"] )); context.ExecuteQuery(); // 遍历输出每个项的字段值 foreach (ListItem item in items) { Console.WriteLine($"项ID: {item.Id}"); // 只输出我们指定的字段(过滤系统字段) foreach (var field in targetFields) { if (item.FieldValues.ContainsKey(field)) { Console.WriteLine($"{field}: {item.FieldValues[field]}"); } } Console.WriteLine("--------------------------"); } } catch (Exception ex) { Console.WriteLine($"错误信息: {ex.Message}"); if (ex.InnerException != null) { Console.WriteLine($"内部错误: {ex.InnerException.Message}"); } } } } } }
关键说明
- 身份验证:使用
GetACSAppOnlyContext方法实现仅应用的ACS身份验证,和PowerShell中应用权限的认证方式一致,确保无需用户交互即可访问SharePoint。 - 字段加载优化:通过
Include方法明确指定要加载的字段,避免默认加载所有字段,提升请求性能,这和PowerShell的-Fields参数作用完全匹配。 - FieldValues获取:直接访问
ListItem.FieldValues属性,返回和PowerShell命令中一致的字段名-值键值对集合。 - 可选调整:如果需要筛选特定列表项,可以修改
CamlQuery的查询条件;如果不需要过滤系统字段,直接遍历item.FieldValues即可。
内容的提问来源于stack exchange,提问作者user1005310
相关产品推荐
相关产品推荐

