Search This Blog

Tuesday, May 10, 2011

How to delete all items from site recycle bin permanently : Sharepoint 2007

We often need to empty the recycle bin of the site collection in sharepoint to free up space.Now, in sharepoint, there are 2 stages in the recycle bin.The first stage is the user recycle bin where all the deleted items are added when they are deleted in the site.
The second stage is the admin recycle bin and is used to retain all deleted items for a configurable period of time (usually 30 days).In order to delete all the items from the admin recycle bin permanently,we have to first move the items to the second stage and then delete them permanently

We can use the following code to accomplish the same:

private void btnEmptyRecyclebin_Click(object sender, EventArgs e)
        {
            string siteURL = txtSiteUrl.Text;
            EmptySiteRecycleBin(siteURL);
        }

        public void EmptySiteRecycleBin(string siteURL)
        {
           
            try
            {

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(siteURL))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            web.AllowUnsafeUpdates = true;

                            site.RecycleBin.MoveAllToSecondStage();

                            //Empty the items from the SiteRecycleBin (the second stage recycle bin)                          
                            if (site.RecycleBin.BinType == SPRecycleBinType.SiteRecycleBin)
                            {
                                //Delete all the items                         
                                site.RecycleBin.DeleteAll();
                            }




                        }

                    }

                });

                MessageBox.Show("Recycle bin cleaned up!!.");
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occurred while emptying recycle bin.");
              

            }


        }


The code first moves all items to the second stage and then deletes them permanently.

This is the code for a windows application but can also be used in sharepoint after making a few changes.



No comments:

Post a Comment