Delete specific file from attachment of a list item programatically

Updated: Sep 15, 2020

Consider you have a listitem with multiple files added as attachments. Now you need to delete a specific file from those attachments programmatically, follow below steps:

  public static void DeleteAttachment(int itemId, string fileName)  
	  using (SPSite site = new SPSite("http://server/sites/sitename"))  
		  using (SPWeb web = site.OpenWeb())  
			  SPListItem listItem = web.Lists.TryGetList("Employees").GetItemById(itemId);  

			  List fileNames = new List();  
			  if(listItem.Attachments.Count > 0){
				  //Store all file names from attachment collection
				  foreach (string fileName in listItem.Attachments){  

			  if(fileNames.Count > 0 && fileNames.Contains(filename)){  

Now make a call to the method

int itemID = 10;
string filename = "address.docx";
DeleteAttachment(itemId, fileName);

1 view0 comments

Recent Posts

See All

In this blog we will see how to export a list in excel using server side object model. First block we will retrieve all items from the list. This can be done in several ways. You can get all items wit