Traversing a SP hierarchy in C#
October 27, 2007
At the risk of being mocked for my lacking C# skillz, I thought I’d post another code snippet.
(And at the risk of losing traffic, because it seems that whenever I post code, Google stops sending me traffic for a couple days.)
One thing we have encountered as part of our migration is the need to make a change to an entire environment. (Modifying ACLs, etc.) In Notes, AdminP can do some of this for you, but when the change needs some calculated logic, you need to script it. Notes has the NotesDbDirectory object which handles this nicely for you.
But it got me thinking – what if you wanted to traverse your entire SharePoint environment? What would that code look like? So I sat down this morning, and spit out the code below.
It is just a recursive call to each site’s subsites, which gives you an opportunity to do something at each site.
static void Main(string[] args)
{
SPSite rootSite = new SPSite(”http://yourserver”);
SPWeb site;
SPWebCollection children; site = rootSite.OpenWeb();
DoYourStuff(site);
//Traverse SP hierarchy
children = site.GetSubwebsForCurrentUser();
if (children.Count > 0)
{
ProcessChildren(children);
}
}
static void ProcessChildren(SPWebCollection sites)
{
foreach (SPWeb site in sites)
{
DoYourStuff(site);
SPWebCollection children;
children = site.GetSubwebsForCurrentUser();
if (children.Count > 0)
{
ProcessChildren(children);
}
}
}
August 3, 2008 at 3:47 am
Tahnks for posting
April 14, 2009 at 1:58 pm
The style of writing is quite familiar . Have you written guest posts for other bloggers?