Tuesday, August 13, 2013

Using C# to read data from a SharePoint list using the SharePoint REST API

If you're working with a C# application that is required to read information contained in a SharePoint list located on an external SharePoint farm, the SharePoint REST API can provide just the solution that you're looking for.  Here is some sample code that you can use for accessing the information contained in that SharePoint list:

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Web.Script.Serialization;

namespace Sample
{
    public class SharePointListReader
    {
        ...

        public List<SharePointListItem> GetAllSPListItems()
        {
            List<SharePointListItem> posts = new List<SharePointListItem>();
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://webapp/site/_api/web/lists/getbytitle('listName')/items?$select=id,Title");
            request.Method = "GET";
            request.Accept = "application/json;odata=verbose";
            request.ContentType = "application/json;odata=verbose";
            request.Credentials = System.Net.CredentialCache.DefaultCredentials;
            WebResponse response = request.GetResponse();
            Data data = null;

            // Read the returned posts into an object that can be consumed by the calling application
            using (response)
            {
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    try
                    {
                        string jSON = reader.ReadToEnd();
                        data = serializer.Deserialize(jSON);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(string.Format("An error occurred when reading the list items from SharePoint: {0}; {1}", ex.Message, ex.StackTrace));
                    }
                }
            }
            foreach (SharePointListItem post in data.d.results)
            {
                posts.Add(post);
            }
            return posts;
        }
    }

    public class Data
    {
        public Results d { get; set; }
    }

    public class Results
    {
        public SharePointListItem[] results { get; set; }
    }

    public class SharePointListItem
    {
        public string id { get; set; }
        public string Title { get; set; }
    }
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.