Wednesday, January 16, 2013

11:17 PM

In this post we will discuss about how to add an attachment using SharePoint 2010 object model.

You can also check my previous posts on Get 14 hive file path by using SharePoint 2010 object model [Read here], Get URL value SharePoint hyperlink field [Check here] and How to get Absolute URL of List using SharePoint object model? [Solution here].

string listItemID = "ID of the list item";

using (SPSite site = new SPSite("http://Site URL"))
using (SPWeb web = site.OpenWeb())
SPList list = web.Lists["MyCustomList"];
SPListItem newItem = list.GetItemById(listItemID);

byte[] contents = null;

if (fileUpload1.PostedFile != null && fileUpload1.HasFile)

using (Stream fileStream = fileUpload1.PostedFile.InputStream)
contents = new byte[fileStream.Length];
fileStream.Read(contents, 0, (int) fileStream.Length);

SPAttachmentCollection attachments = newItem.Attachments;
string fileName = Path.GetFileName(fileUpload1.PostedFile.FileName);
attachments.Add(fileName, contents);
newItem ["AttachmentName"] = fileName;


Here fileUpload1 is the file uploaded control. And AttachmentName is the column name in the list.


Post a Comment