Site Collection Node Iteration Issue in SharePoint 2010
I am iterating through my Site Collections in SharePoint for a custom navigation. But I am trying to only allow the iteration to output nodes from one level deep after /sites/. For example, sites/IT.
At the moment, my method is iterating through all nodes. For example, sites/IT/Support.
private void GetSiteChildNodes(string siteName)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
foreach (SPSite site in SPContext.Current.Site.WebApplication.Sites)
{
try
{
if (SPSite.Exists(new Uri(site.Url)) && site.ServerRelativeUrl.StartsWith(String.Format("/sites/{0}/", siteName)))
{
SPWeb subSites = site.RootWeb;
foreach (SPWeb cn in subSites.Webs)
{
navBuilder.AppendFormat("<li>开发者_JAVA百科<a href=\"{0}\">{1}</a></li>", cn.Url, cn.Title);
}
}
}
finally
{
site.Dispose();
}
}
});
}
As you can see from my code, I am using "RootWeb" so that I ignore any child nodes from within the site. But that is not working.
Any help would be appreciated.
Try this:
using (SPSite oSiteCollection = new SPSite("http://<>")) { SPWeb web = oSiteCollection.OpenWeb("sites");
foreach (SPWeb oWebsite in web.Webs)
{
Console.WriteLine("Web site: {0}", oWebsite.Url);
oWebsite.Dispose();
}
}
Upon reading your comment, @R100, if you have managed paths defined for your subsites, then each managed path (no matter the logical hierarchy you put into place) is at the same level in the SPWebApplication.Sites collection.
For example, if you have the following hierarchy:
- Root (/) [Site Collection]
- Sites (/sites) [Site Collection]
- IT (/sites/IT) [Site Collection]
- Support (/sites/IT/Support) [Site Collection]
then SPWebApplication.Sites will contain each of those above in a flattened collection.
Additionally, the ServerRelativeUrl for site collections is all relative to the root of the SharePoint installation. Thus, what you see in the parenthesis in the above hierarchy is the ServerRelativeUrl for each of the nodes.
Thus, your check when you're iterating over your values is true for each child site collection under /sites/it (if it is the siteName you are passing down):
site.ServerRelativeUrl.StartsWith(String.Format("/sites/{0}/", siteName))
精彩评论