Sunday, 19 June 2011

Adding an Attachment to an Item

Below code can be used to add attachment to list item.

using (SPSite site = new SPSite("http://SiteCollectionURL"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["MyListName"];
SPListItem newItem = list.GetItemById(id);
byte[] contents = null;
if (fileUpload.PostedFile != null && fileUpload.HasFile)
{
using (Stream fileStream = fileUpload.PostedFile.InputStream)
{
contents = new byte[fileStream.Length];
fileStream.Read(contents, 0, (int) fileStream.Length);
fileStream.Close();
}
SPAttachmentCollection attachments = newItem.Attachments;
string fileName = Path.GetFileName(fileUpload.PostedFile.FileName);
attachments.Add(fileName, contents);
newItem.Update();
}
}
}

No comments:

Query List/Document Library in Specific Folder

To query SharePoint List or Document Library in specific Folder “ FolderServerRelativeUrl ” as part of the CAML Query Code Snippet ...