02/22/2010

Best way to get an SPWeb Object

Getting an SPWeb object can be done in a bunch of different ways, and it depends on whether or not your code is running in a sharepoint context. If you are in a sharepoint context, you dont need to use the 'using' statements, in my experience you only need to use those if you are not in a sharepoint context.

Here is some code we use to get SPWeb objects. At first we were doing it a different way, but after exhaustive testing and running into multiple bugs that stemmed from the way we got spwebs in the past, we think weve got a solution that should work for most configurations.

Inside a sharepoint context:

/// <summary>

/// Gets a SharePoint web site object from its Guid

/// </summary>

/// <param name="guid"></param>

/// <returns></returns>

public static SPWeb getSPWeb(Guid guid)

{

SPWeb web = GetSPWebCollectionFromCurrentSite()[guid]; // don't want to return this spweb since it has admin privileges

return getRootSPSite().OpenWeb(web.ID);

}

public static SPSite getRootSPSite()

{

return SPContext.Current.Site;

}

/// <summary>

/// Gets the collection of all the sites in the site collection.

/// </summary>

/// <param name="site">A SharePoint site collection</param>

/// <returns>The collection of all the sites in the site collection</returns>

public static SPWebCollection GetSPWebCollectionFromSite(SPSite site)

{

SPUserToken token = site.SystemAccount.UserToken;

SPSite elevatedSiteCollection = new SPSite(site.ID, token);

return elevatedSiteCollection.AllWebs;

}

/// <summary>

/// Gets the collection of all the sites in the current site collection (so this is context specific).

/// </summary>

/// <returns> Collection of all the sites in the current site collection</returns>

public static SPWebCollection GetSPWebCollectionFromCurrentSite()

{

return GetSPWebCollectionFromSite(SPContext.Current.Site);

}

Im now just noticing that we dont check against current user permissions, but so far from our testing this hasnt been a problem.

If you are outside of the SPContext then use this stuff instead. This assumes that you can get the URL for the site, or whatever resource you are trying to access. In our case we are trying to get at a file, so if you pass in the full url of the file, it will pick the correct spsite for you.