Monday, May 13, 2013

Deleting items from Document Library efficiently

I needed to delete all the items from a temporary document library placeholder. So I created a timer job which constantly cleans up the library. Here is the code

Prepare the command builder as follows. Make sure:
  • owsfileref is set to the complete location of the file (Ex: http://server/site/site1/list/documentmame.ext)
  • Cmd is set to Delete
  • Type is set to 1
        private static StringBuilder BatchCommandDocument(SPList spList, SPSite site)
            StringBuilder deleteBuilder = new StringBuilder();
            string command = "" + spList.ID +
            foreach (SPListItem item in spList.Items)
                     string.Format(command, site.Url + "/Lists/LISTNAME/" + item["Name"].ToString(), item.ID));
            return deleteBuilder;
The above method generates a string to batch delete all the items in the document library. Call the method as under.
        public static void CleanupList(SPSite site)
            if (site == null)
                site = SPContext.Current.Site as SPSite;

                    SPWeb web = site.OpenWeb();
                    SPList list = web.Lists["LISTNAME"];
                    StringBuilder deleteBuilder = BatchCommandDocument(list, site);
                    if (deleteBuilder != null)
                        web.AllowUnsafeUpdates = true;
                        web.AllowUnsafeUpdates = false;
                catch (Exception ex)
                    //Handle the exception

No comments:

Post a Comment