Sharepoint and REST - WebClient - Add Attachment to List Item


Problem Definition

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

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 WebClient
/// </summary>
public class SharePointAndRest_WebClient : IDisposable
{
        private WebClient webClient;
        public Uri WebUri { get; private set; }

        public SharePointAndRest_WebClient(Uri webUri)
        {        
            WebUri = webUri;
        }

        public string UploadFileToItem_WebClient(string listTitle, int id,string filePath)
        {
            webClient = new WebClient();
            webClient.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
            var formDigestValue = GetFormDigest();
            webClient.Headers.Add("X-RequestDigest", formDigestValue);
            var endpointUri = new Uri(WebUri, string.Format("_api/web/lists/getbytitle('{0}')/items({1})/AttachmentFiles/add(FileName='{2}')", listTitle, id,"myTextFile_WebClient.txt"));
            webClient.Headers.Add(HttpRequestHeader.ContentType, "text/xml");
            webClient.Headers.Add(HttpRequestHeader.Accept, " text/html, application/xhtml+xml, */*");
            webClient.UseDefaultCredentials = true;
            var response = webClient.UploadFile(endpointUri,"POST" ,filePath);
            return System.Text.Encoding.ASCII.GetString(response);
        }

        /// <summary>
        /// Provides form data digest
        /// </summary>
        /// <returns></returns>
        private string GetFormDigest()
        {
            webClient = new WebClient();
            webClient.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
            webClient.Headers.Add(HttpRequestHeader.ContentType, "application/json;odata=verbose");
            webClient.Headers.Add(HttpRequestHeader.Accept, "application/json;odata=verbose");
            webClient.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0+(compatible;+MSIE+5.01;+Windows+NT+5.0");
            webClient.UseDefaultCredentials = true;
            var endpointUri = new Uri(WebUri, "_api/contextinfo");
            var result = webClient.UploadString(endpointUri, "POST");
            JToken t = JToken.Parse(result);
            return t["d"]["GetContextWebInformation"]["FormDigestValue"].ToString();
        }

        /// <summary>
        /// IDisposable Implementation
        /// </summary>
        public void Dispose()
        {
            webClient.Dispose();
            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 WebClient
/// </summary>
public static void SharepointAndRest_UploadFileToItem_WebClient()
{
            //var webUri = new Uri(@"http://<your server>/<site>/");
            using (var client = new SharePointAndRest_WebClient(webUri))
            {           Console.WriteLine(client.UploadFileToItem_WebClient("MessageTest",3,@"c:\Temp\TextFile.txt"));
            }
}

Result


Also Look at

Sharepoint and REST - WebClient - Get List Data
Sharepoint and REST - WebClient - Insert Data to List
Sharepoint and REST - WebClient - Update Data to List
Sharepoint and REST - WebClient - Delete Data from List



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)