Introducing the SharePoint object model
As an alternative to programming against the SharePoint web services you can use the SharePoint object model. The object model can be used when the application will run on the server where SharePoint is installed (such as a console or WinForm application) or in assemblies that are run within a site (such as a Web Part).
This sample shows how to display the sites and sub sites within a site collection as a hierarchy in a tree view control within a WinForm application.
First, you will need to create a reference to “SharePoint.dll” assembly in your Visual Studio 2005 project. This is located at:
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI\Microsoft.SharePoint.dll
A recursive function nicely solves the problem of loading the site hierachy into a tree view control. The method below is passed the tree node into which the site list will be loaded, and a SPWeb object representing the site whose sub-sites will be loaded:
private void FillSubWeb(TreeNode tn, SPWeb webSite)
foreach (SPWeb theWeb in webSite.Webs)
TreeNode subTN = new TreeNode(theWeb.Name);
This method iterates over the “Webs” collection which returns each sub-site. A new TreeNode object is created with the site name. The node is added to the tree view control. Lastly, the FillSubWeb method is called recursively, passing the TreeNode and theWeb object to load the sub-sites for the current site.
The following code kicks off the loading of the sites:
The code gets a reference to the site collection from the URL, and then obtains a reference to the top-level web (site) for the site collection. A tree node is created and added to the tree view control to represent the site collection, and then the FillSubWeb method is called to start the recursive process.