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();
            deleteBuilder.Append("");
            string command = "" + spList.ID +
                "{0}
                 Delete
                 {1}1";
            foreach (SPListItem item in spList.Items)
            {
                deleteBuilder.Append(
                     string.Format(command, site.Url + "/Lists/LISTNAME/" + item["Name"].ToString(), item.ID));
            }
            deleteBuilder.Append("");
            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;

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

No comments:

Post a Comment