There are two methods to do this: one method applies when your
code will be used in a console or Windows-based application; the other applies
when your code will be used in a browser-hosted application, such as when you
choose "Web Site" as the type of Microsoft Visual Studio project.
To
work with a deployment of SharePoint Foundation by means of a browser-hosted
application, your code must first establish the site context or site collection
context for requests that are made to the server.
You must obtain the HTTP context of the request in the
code. Microsoft recommends that you do this by using the Microsoft.SharePoint.SPContext class and its members.
Some examples are as follows.
SPSite oSiteCollection = SPContext.Current.Site;
SPWeb oWebSite = SPContext.Current.Web;
SPWeb oWebSite = SPControl.GetContextWeb(Context);
SPWeb oWebSite = this.Web;
To
return the current top-level server farm object, use SPContext.Current.Site.WebApplication.Farm.
SPFarm myFarm = SPContext.Current.Site.WebApplication.Farm;
SPWeb oTopSite = SPContext.Current.Site.RootWeb;
The SPContext class
has no meaning in a console or Windows-based application. If you are writing
code for either of those types of applications and you want to work with a specific
site collection, use the SPSite constructor to instantiate an object that represents the site
collection, as in the following example.
SPSite
oSiteCollection
= new
SPSite("http://localhost");
oSitecollection.Dispose();
//
Even better, take advantage of a "using" block to ensure
using
(SPSite oSiteCollection = new SPSite("http://localhost"))
{
……..
}
No comments:
Post a Comment