Adding an Attachment to a List Item Programmatically in SharePoint
As we can have multiple attachments against a list item, it has always been a requirement to fetch these attachments and get it displayed within a custom webpage.
Below is code snippet in c#.net for fetching all the attachements for a specific list item.
try
{
// Set the Site Url
SPSite objSite = new SPSite("http://Testsite/");
using (SPWeb objWeb = objSite.OpenWeb())
{
objWeb.AllowUnsafeUpdates = true;
// Get the List
SPList objList = objWeb.Lists["MyList"];
// Get the item by ID
SPListItem objItem = objList.GetItemById(1);
// Get the attachments of the item
SPAttachmentCollection objAttchments = objItem.Attachments;
Thanks
Re: Adding an Attachment to a List Item Programmatically in SharePoint
Do you know how to add docx attachment to list programmatically? I have gone through the below code snippet in c#.net for fetching all the attachements for a specific list item which I think isnt correct, so can you let me know about same:
Code:
{
// Set the Site Url
SPSite objSite = new SPSite("http://Testsite/");
using (SPWeb objWeb = objSite.OpenWeb())
{
objWeb.AllowUnsafeUpdates = true;
// Get the List
SPList objList = objWeb.Lists["MyList"];
// Get the item by ID
SPListItem objItem = objList.GetItemById(1);
// Get the attachments of the item
SPAttachmentCollection objAttchments = objItem.Attachments;
Re: Adding an Attachment to a List Item Programmatically in SharePoint
In case you need to do the upload the file as an attachment to a custom list using the object model, the approach is slightly different. Adding a file to the list item can be done by accessing the Attachments collection of the SPListIem.