The idea here might look really crazy. But on a few occasions, I’ve had to loop through an entire SharePoint Farm in search of a list with a unique title (and then create the corresponding SPList object).
One time I’ve had to do this was when passing control to an aspx page in the layouts folder from a modal dialog that was just closed.
A common way I would normally get my SPList object is to create it from an SPWeb object using spweb.Lists.TryGetList(). In this particular case, however, the SPContext object held no useful information that could help me easily grab a relevant SPSite or SPWeb object.
So here’s how I did it:
SPSecurity.RunWithElevatedPrivileges(delegate() { SPServiceCollection services = SPFarm.Local.Services; foreach (SPService curService in services) { if (!(curService is SPWebService)) continue; SPWebService webService = (SPWebService)curService; foreach (SPWebApplication webApp in webService.WebApplications) { for (int i = 0; i < webApp.Sites.Count; i++) { using (SPSite site = webApp.Sites[i]) { using (SPWeb masterWeb = site.RootWeb) { SPList list = null; list = masterWeb.Lists.TryGetList("Your List Title"); if (list != null) { // Now you can work with the SPList object here. } } } } } } });
It’s very possible that there is an easier way of handling this situation and achieving the same results. Do you know a simpler method? Please post it in your comment below.
Leave a Reply