GSCustomMenuSection

Contents for SharePoint, ReactJS, C#, ASP .Net, JavaScript, JQuery, SQL

Monday, March 14, 2016

Delete specific file from attachment of a list item programatically

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){  
                           fileNames.Add(fileName);  
                      }  
                  }

                  if(fileNames.Count > 0 && fileNames.Contains(filename)){  
                      listItem.Attachments.Delete(fileName);                        
                  }  
                   
                  listItem.update();
              }   
          }                     
      } 

Now make a call to the method

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


No comments :

Post a Comment