SharePoint开发——利用CSOM逐级获取O365中SharePoint网站的List内容

来源:互联网 发布:淘宝怎么让买家改评价 编辑:程序博客网 时间:2024/05/08 15:07
博客地址:http://blog.csdn.net/FoxDave

本文介绍如何利用SharePoint客户端对象模型(.NET)逐级获取Office 365网站中List的内容,仅仅是示例,没有讲究太多东西。

代码如下:

ClientContext ctx = new ClientContext("<your sharepoint site url>");            ctx.Credentials = new SharePointOnlineCredentials("username", GetSecurePassword("password"));            Web web = ctx.Web;                       List list = web.Lists.GetByTitle("List");            ctx.Load(list, l => l.RootFolder, l => l.RootFolder.ServerRelativeUrl);            ctx.ExecuteQuery();            stringBuilder = RetrieveItems(ctx, list, list.RootFolder, 0);            Console.WriteLine(stringBuilder.ToString());

首先第一部分是构建SharePoint Online的Context对象,授权认证那里使用SharePointOnlineCredentials这个对象,这个对象构造函数的参数需要类型为字符串的用户名和类型为SecureString的密码,这里使用GetSecurePassword这个方法来构建密码参数,代码将在下面列出。

第二部分,利用Context对象获取指定的List,进而获取里面的内容。逐级获取需要一个递归去实现,如上的RetrievevItems方法,同样会在下面说明。

最后输出获取的内容,stringBuilder为全局的StringBuilder对象,用来保存读取到的信息。

GetSecurePassword方法的代码如下:

private static SecureString GetSecurePassword(string pwd)        {            //Get the user's password as a SecureString            SecureString securePassword = new SecureString();            char[] pwdArray = pwd.ToCharArray();            for (int i = 0; i < pwdArray.Length; i++)            {                securePassword.AppendChar(pwdArray[i]);            }            return securePassword;        }

方法的返回类型为SecureString。方法体中,首先构建一个SecureString对象,并将密码字符串转成char数组,然后执行AppendChar方法把依次将char数组的字符传入,最后返回这个对象就可以了。

RetrievevItems方法的代码如下:

private static StringBuilder RetrieveItems(ClientContext ctx, List list, Folder folder, int level)        {            level++;            CamlQuery query = new CamlQuery();            query.FolderServerRelativeUrl = folder.ServerRelativeUrl;            ListItemCollection listItems = list.GetItems(query);            ctx.Load(listItems);            ctx.ExecuteQuery();            foreach (ListItem item in listItems)            {                if (item.FileSystemObjectType == FileSystemObjectType.Folder)                {                    ctx.Load(item.Folder);                    ctx.ExecuteQuery();                    stringBuilder.AppendLine(string.Format("Level: {0}, Folder: {1}", level, item["Title"]));                    return RetrieveItems(ctx, list, item.Folder, level);                }                else                {                    stringBuilder.AppendLine(string.Format("Level: {0}, Item: {1}", level, item["Title"]));                }            }            return stringBuilder;        }
参数level表示当前的深度。在使用客户端对象模型获取列表的Item时,需要传入一个CamlQuery对象,为该对象的FolderServerRelativeUrl属性赋值来控制要获取Item的位置。然后对获取到的当前级别的Item集合进行遍历,如果存在文件夹,则进一步遍历,通过这个递归方法进行了实现。

0 0
原创粉丝点击