Sharepoint and REST - HttpWebRequest - Add Attachment to List Item


Problem Definition

Add attachment to SharePoint list item using REST API and HttpRequest.

Prerequisites

In order to effectively deal with the data in the SharePoint List I will recommend using Newtonsoft.JSON that makes dealing with List data a lot easier.

In order to get JSON plugin go to NuGet and search for JSON.NET or NEWTONSOFT


SharePointAndRest_WebClient.cs

class dealing with SharePoint Data posting:



Code Help

/// <summary>
/// Implement Sharepoint Functionality using httprequest
/// </summary>
public class SharePointAndRest_HttpWebRequest : IDisposable
{
        private HttpWebRequest httpWebRequest;
        public Uri WebUri { get; private set; }

        /// <summary>
        /// Intialize request
        /// </summary>
        /// <param name="webUri">Basic url to sharepoint site</param>
        public SharePointAndRest_HttpWebRequest(Uri webUri)
        {
            WebUri = webUri;
        }
     
        /// <summary>
        /// Upload FIle to Sharepoint 2013 using REST and HttpRequest
        /// </summary>
        /// <param name="listTitle">List Title</param>
        /// <param name="id">ID to attach file to</param>
        /// <param name="filePath">Path of file to attach</param>
        /// <returns></returns>
        public string UploadFileToItem_HttpWebRequest(string listTitle, int id, string filePath)
        {
            var requestUrl = string.Format("{0}/_api/web/Lists/GetByTitle('{1}')/items({2})/AttachmentFiles/add(FileName='{3}')", WebUri, listTitle, id, "myTextFile_HttpWebRequest.txt");
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUrl);
            httpWebRequest.Credentials = CredentialCache.DefaultCredentials;
            httpWebRequest.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
            httpWebRequest.Method = "POST";
            httpWebRequest.Headers.Add("X-RequestDigest", GetFormDigest());
            var fileContent = File.ReadAllBytes(filePath);
            httpWebRequest.ContentLength = fileContent.Length;
            using (var requestStream = httpWebRequest.GetRequestStream())
            {
                requestStream.Write(fileContent, 0, fileContent.Length);
            }
            var response = (HttpWebResponse)httpWebRequest.GetResponse();
            return response.StatusDescription;
        }

        /// <summary>
        /// Provides form data digest
        /// </summary>
        /// <returns></returns>
        private string GetFormDigest()
        {
            string formDigest;
            var endpointUri = new Uri(WebUri, "_api/contextinfo");
            HttpWebRequest wreq = HttpWebRequest.Create(endpointUri) as HttpWebRequest;
            wreq.Credentials = CredentialCache.DefaultNetworkCredentials;
            wreq.Method = "POST";
            wreq.ContentLength = 0;
            WebResponse wresp = wreq.GetResponse();
            using (var sr = new StreamReader(wresp.GetResponseStream()))
            {
                var data = sr.ReadToEnd();
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(data);
                XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
                manager.AddNamespace("d", "http://schemas.microsoft.com/ado/2007/08/dataservices");
                formDigest = doc.SelectSingleNode("/d:GetContextWebInformation/d:FormDigestValue", manager).InnerText;
            }
            return formDigest;
        }


        /// <summary>
        /// IDisposable Implementation
        /// </summary>
        public void Dispose()
        {
            httpWebRequest = null;
            GC.SuppressFinalize(this);
            GC.Collect();
        }
    }

SharePointAndRest.cs

Method calling SharePointAndRest_WebClient Class:


Code Help

 /// <summary>
 /// This method supplies the id and calls the execution of file attachment to list id using Http
 /// </summary>
 public static void SharepointAndRest_UploadFileToItem_HttpWebRequest()
 {
       //var webUri = new Uri(@"http://<your server>/<site>/");
       using (var client = new SharePointAndRest_HttpWebRequest(webUri))
       {
           Console.WriteLine(client.UploadFileToItem_HttpWebRequest("MessageTest", 3, @"c:\Temp\TextFile.txt"));
            }
        }
}

Result






Comments

Popular posts from this blog

Azure - Manage Blob Storage - Part #7 - Add Metadata to an Existing Container using C#

Azure - Manage Blob Storage - Part #5 - Create Folder Structure and upload a file to folder using an Existing Container using C#

Algorithm - Breadth First Search(BFS) - Python(3)