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);             
                


            }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }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

  1. Pingback: Programmatically add attachments to custom list using SharePoint 2010 Client Object Model - My experiments with SharePoint, Azure and .NET using Visual Studio

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.