Tuesday, April 10, 2012

Delete File from SharePoint document library using Client context

Leave a Comment
Following blog spot shows how to delete file from sharepoint site document library using client context. To demonstrate this, we will delete first file from file collection.


To start with the code, we will create console application.
Add 2 assemblies to the sharepoint project
(1) Microsoft.Sharepoint.Client
(2) Microsoft.SharePoint.Client.Runtime

Both assemblies resides inside 14 hive\ISAPI Folder

Inside Main Function write following code.

         // Get Web object

          ClientContext clientContext = new ClientContext("site url");
          Web web = clientContext.Web;


          // Get List Object
          List list = web.Lists.GetByTitle("ListName");
          clientContext.Load(list);
   
          // Get Root Folder for the List
          Folder folder = list.RootFolder;
          clientContext.Load(folder);


          // Get File Collection
          FileCollection files = folder.Files;
          clientContext.Load(files);
          clientContext.ExecuteQuery();


         //Delete first file from the collection
          File file = files[1];          
          file.DeleteObject();
          clientContext.ExecuteQuery();


0 comments: