How to avoid Access Denied error while using AllWebs
December 21, 2009 Leave a comment
Hwile running SPSecurity.RunWithElevatedPrivileges we can brows AllWebs whithout hitting the Access denied wall (c: Her’s how it gows
StringBuilder sb = new StringBuilder(); SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite sitecol = new SPSite(sharePointRootSite)) { sb.AppendFormat("{0}", "<ul>"); foreach (SPWeb web in sitecol.AllWebs) { if (web.DoesUserHavePermissions(login, SPBasePermissions.ViewPages)) sb.AppendFormat("<li><a href='{0}'>{1}</a></li>", web.Url, web.Title); } sb.AppendFormat("{0}", "</ul>"); } });
This way you only have to show the user only the sites which he/she have promissions to se.
Another good thing is by wraping our statement in a using statement it handles the disposing of IDisposable objects by it self.
it essentially calls .Dispose() when it is done.