Programmatically add attachments to custom list using SharePoint 2010 Client Object Model

Home | SharePoint Development | Programmatically add attachments to custom list using SharePoint 2010 Client Object Model

One of the important capability of SharePoint 2010 Managed Client Object model it its ability to add attachments to custom list. This capability is provided by the Microsoft.SharePoint.Client.File class in the client side APIs. The whole idea is to directly invoke the SaveBinaryDirect method of the Microsoft.SharePoint.Client.File class and pass the parameters like ClientContext, attachment path, filestream object and a boolean flag to set the overwrite status.

  using (ClientContext clientContext = new ClientContext("http://yoursitecollection"))
            {

                Web oWeb = clientContext.Web;
                List oList = oWeb.Lists.GetByTitle("NewCustomList");               
                FileStream oFileStream = new FileStream(@"C:SundarTestFile.txt",FileMode.Open);
                string attachmentpath = "/Lists/NewCustomList/Attachments/2/TestFile.txt";
                clientContext.Load(oList);
                clientContext.ExecuteQuery();
                Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, attachmentpath, oFileStream, true);             
                


            }

The important point to consider here is how to frame the attachment path url for adding attachment. The attachment url needs to be in the following format :-

“/Lists/NameoftheList/Attachments/ItemNumber/AttachmentFile.extension

NameoftheList – is the name of the custom list where you want you add attachments

ItemNumber – is the id of the custom list item

AttachmentFile.extension – is the file to be attached

 Subscribe to my blog

2 thoughts on “Programmatically add attachments to custom list using SharePoint 2010 Client Object Model

Leave a Reply