我正在尝试在SharePoint Server上获取网站集列表的完整输出,以便我可以枚举它们并收集数据。我找到了以下代码:
foreach (SPWebApplication wa in SPWebService.ContentService.WebApplications)
{
foreach (SPSite sc in wa.Sites)
{
try
{
Console.WriteLine("Do something with site at: {0}", sc.Url);
}
catch (Exception e)
{
Console.WriteLine("Exception occured: {0}\r\n{1}", e.Message, e.StackTrace);
}
finally
{
sc.Dispose();
}
}
}
但不幸的是,这会引发以下错误:
System.NullReferenceException:未将对象引用设置为实例 一个对象。
是否有可能这样做或者我必须提供服务器名称(即使我直接在SharePoint服务器上运行此代码?)
答案 0 :(得分:3)
我认为SPWebservice.ContentService不会为您提供所有服务,也不会为您提供所有WebApp,这段代码对我来说运行正常:
SPServiceCollection services = SPFarm.Local.Services;
foreach(SPService curService in services)
{
if(curService is SPWebService)
{
SPWebService webService = (SPWebService)curService;
foreach(SPWebApplication webApp in webService.WebApplications)
{
foreach(SPSite sc in webApp.Sites)
{
try
{
Console.WriteLine("Do something with site at: {0}", sc.Url);
}
catch(Exception e)
{
Console.WriteLine("Exception occured: {0}\r\n{1}", e.Message, e.StackTrace);
}
}
}
}
}