Thursday 28 July 2016

Get List items in SharePoint Online Through CSOM

Friends, here is quick code snippet to get items of a list in SharePoint Online in CSOM from a Console Application.

Reference to Microsoft.SharePoint.Client.dll to be added.
Replace user name, password and site url with actuals from the code.
Code:

using Microsoft.SharePoint.Client;
using System;
using System.Security;
namespace TestConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string userName = "USERNAME";
            string password = "PASSWORD";
            string siteUrl = "SITEURL";
            ClientContext clientContext = new ClientContext(siteUrl);
            clientContext.Credentials = new SharePointOnlineCredentials(userName, GetPassword(password));
            Web web = clientContext.Web;
            List list = web.Lists.GetByTitle("Announcements");
            CamlQuery querry = CamlQuery.CreateAllItemsQuery(100);
            ListItemCollection items = list.GetItems(querry);
            clientContext.Load(items);
            clientContext.ExecuteQuery();
            foreach (var item in items)
            {
                Console.Write(item["Title"].ToString());
            }
            Console.Read();
        }
        private static SecureString GetPassword(string password)
        {
            if (password == null)
                throw new ArgumentNullException("password");
            var securePassword = new SecureString();
            foreach (char c in password)
                securePassword.AppendChar(c);
            securePassword.MakeReadOnly();
            return securePassword;
        }
    }
}

No comments:

Post a Comment