Tuesday, January 3, 2012

How to delete a site with all sub-sites

SharePoint does not allow user delete the site which has many sub-sites existed. That means if there are many sub-sites are still working, and user try to delete the parent site, the error will throw exception. Here is the piece code to help delete the parent site with long operation.



private void DeleteAllWebs()
        {
            SPLongOperation.Begin(delegate(SPLongOperation longOperation)
            {
                try
                {

                    int lCID = base.Web.Locale.LCID;
                    uint language = base.Web.Language;
                    int uIVersion = base.Web.UIVersion;

                    string layouts = Utilities.DetermineLayoutsUrl(base.Web.ParentWeb, this.Context, false, false);

                    this.DeleteWeb(base.Web);

                    string queryString = string.Concat(new string[]
   {
   "c=",
   lCID.ToString(CultureInfo.InvariantCulture),
   "&ui=",
   language.ToString(CultureInfo.InvariantCulture),
   "&uiv=",
   uIVersion.ToString(CultureInfo.InvariantCulture)
   });
                    longOperation.End(layouts + "webdeleted.aspx", SPRedirectFlags.UseSource, this.Context, queryString);


                }
                catch (Exception ex)
                {
                    logger.Error("DeleteCommunity", ex);
                    throw ex;
                }
            }
            );
        }

        protected void DeleteWeb(SPWeb web)
        {
            if (web.Webs.Count > 0)
            {
                foreach (SPWeb subweb in web.Webs)
                {
                    try
                    {
                        DeleteWeb(subweb);
                    }
                    finally
                    {
                        if (subweb != null)
                            subweb.Dispose();
                    }
                }
            }
            if (web.Exists)
                web.Delete();
        }


Hope this help!

No comments: