Ads

Saturday, 23 March 2013

C# code to add multiple attachments in SharePoint list programmatically

Lets assume we are using file upload through a file upload control which add an attachment to a list item.
using (SPSite oSPsite = new SPSite(http: //website Url/))
{
     using (SPWeb oSPWeb = oSPsite.OpenWeb())
      {
           oSPWeb.AllowUnsafeUpdates = true;
            // Fetch the List
            SPList list = oSPWeb.Lists["MyList"];
            // Get the List item
            SPListItem listItem = list.GetItemById(1);
           
            // Get the Attachment collection
            SPAttachmentCollection attachmentCollection = listItem.Attachments;
            Stream attachmentStream;
            Byte[] attachmentContent;
             // Get the file from the file upload control
            if (this.fileDocAttach.HasFile)
            {
                     attachmentStream = this.fileDocAttach.PostedFile.InputStream;
                 
                     attachmentContent = new Byte[attachmentStream.Length];
                     attachmentStream.Read(attachmentContent, 0, (int)attachmentStream.Length);
                    attachmentStream.Close();
                    attachmentStream.Dispose();
                     // Add the file to the attachment collection
                     attachmentCollection.Add(this.fileDocAttach.FileName, attachmentContent);
            }
            // Update th list item
            listItem.Update();
            oSPWeb.AllowUnsafeUpdates = false;
       }
 }

Now retract all the attachments from a specific sharepoint list item.
try
{
  // Set the Site Url
  SPSite objSite = new SPSite("http://TestsiteUrl/");
  using (SPWeb objWeb = objSite.OpenWeb())
  {
  objWeb.AllowUnsafeUpdates = true;
   // Get the List
  SPList objList = objWeb.Lists["MyListName"];
  // Get the item by ID
  SPListItem objItem = objList.GetItemById(1);
  // Get the attachments of the item
  SPAttachmentCollection objAttchments = objItem.Attachments;
  // Iterate the attachments
  foreach (string fileName in objItem.Attachments)
  {
    // Perform action on the extracted attachment
  }
  objWeb.AllowUnsafeUpdates = false;
  }
}
catch (Exception ex)
{
  MessageBox.Show(ex.Message);
}

No comments:

Post a Comment

Ads