Just Add Code

Finding a SPWeb with one hand behind your back

Well, maybe not one hand behind your back, but what if you only have the ID of the web?  I received this question after presenting a session at the Twin Cities SharePoint Camp.  I knew you could grab an SPWeb if you knew its URL using SPSite.OpenWeb, but what if you only had the ID?

Worst case solution would be to recursively go through all the Webs and SubWebs in order to find one with a matching ID.  Another possible, though horrible, approach would be to query the SharePoint database and get the URL from that.  Both of those are pretty bad approaches to what is seemingly a simple problem.

After spending a couple minutes with the SDK I found there was a much cleaner approach available, SPSite.AllWebs.  SPSite has an AllWebs property that has ALL the webs under it, not just the top level ones.  It also has an indexer on it that takes in a guid, giving us our perfect Web by ID scenario.

PowerShell Code:

$site = new-object Microsoft.SharePoint.SPSite("http://mysite/")
$siteid = new guid("22625614-bb87-4cb1-a817-52f8a7366640")
$web = $site.AllWebs[$siteid]

Result: http://mysite/toplevel/secondlevel/YouFoundMe


1 comment Digg this

1 Comment so far

  1. Solutionizing in SharePoint June 14th, 2008 10:58 pm

    Finding an SPWebApplication by ID…

    Not sure if it was me that prompted Neil’s post, but a question that came up earlier today was how to retrieve an SPWebApplication from its ID. Neil suggested trying to retrieve the generic SPPersistedObject by that ID, which eventually led me to…

Leave a reply