0

I am trying to delete the attachments from my SharePoint 2013 list Programmatically :

foreach (string attachment in listitem.attachments)

{

  listitem.attachments.delete(attachment);
  listitem.update();

}

i am able to delete if there is only one attachment , but if i add multiple attachmemnts , on the second loop it gives me error : "collection was modified enumeration operation may not execute".Any idea how i can delete multiple attachments.

  • Not related to exception you have but listitem.update(); is not needed when deleting attachments – Martin P. Mar 8 '16 at 11:34
  • @Revenant_01 could you please test if the snippet in my answer works fine? I've upvoted your answer, just want the code to host in SP.SO – Aziz Kabyshev Mar 8 '16 at 13:13
1

You are changing listitem.attachments inside foreach that was launched on that collection, that's why it's not going to work.

Try something like this:

int count = item.Attachments.Count
for(int i = 0; i < count; i++)
{
    // action with item.Attachments[0] or item.Attachments.Delete(0)
}

UPDATE: My bad, SPAttachmentCollection's indexer returns a filename as string, that is then to be passed to Delete or DeleteNow method. DeleteNow is faster and easier to read in code:

If you delete an attachment by using the DeleteNow method, the deletion takes effect immediately and you do not need to update the list item to refresh version information

Snippet I posted first will work when dealing with SPListItemCollection. To delete from SPAttachmentCollection, this should work:

int count = item.Attachments.Count
for(int i = 0; i < count; i++)
{
    item.Attachments.DeleteNow(item.Attachments[0])
}
  • 1
    For deleting objects you should really use a reverse for-statement – Robert Lindgren Mar 8 '16 at 13:22
  • for(int i = count - 1; i >= 0; i--) and then [i]? Are you sure? I've always used usual for and i-less body without any troubles – Aziz Kabyshev Mar 8 '16 at 13:25
  • 1
    I see now that you use [0] on each iteration, so that would work the same :) – Robert Lindgren Mar 8 '16 at 13:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.