What is difference between SPContext.Current.Web.URL and SPContext.Current.Site when using SPSite object?

sharepoint.stackexchange https://sharepoint.stackexchange.com//questions/95812

  •  10-12-2019
  •  | 
  •  

Question

SPSite spsite1=new SPSite(SPContext.Current.Web.URL);

SPSite spsite2=SPContext.Current.Site;

What is the difference and when do we decide which one to use?

I feel both give us the site collection object.

Example: SPWeb spweb=spsite1.RootWeb; will mean same as spsite2.RootWeb; Then why are there 2 ways to do it?

Was it helpful?

Solution

SPSite spsite1=new SPSite(SPContext.Current.Web.Url); will give you SPSite object. But it will be site collection object only when SPContext.Current.Web.Url is that of root web. If the web object is that of a sub site then SPSite object won't be a site collection object. The second statement SPSite spsite2=new SPSite(SPContext.Current.Site); is wrong because there is no overload of SPSite which has SPSite as parameter.

UPDATE

If the intention is to get the rootweb then second is a better way of doing it as you are not instantiating a new SPSite object. Moreover, in the first case you will need to dispose SPSite object as you are creating a new one compared to second in which SPSite is retrieved through SPContext which should not be disposed explicitly.

OTHER TIPS

The both site1 and site2 returns the same site collection (SPSite) object. By calling RootWeb property on both objects, We can get the same top-level web site (SPWeb) object.

Instruction1: SPSite spsite1=new SPSite(SPContext.Current.Web.URL);

Process: If we are in subsite and we are calling the above code, first it get the current subsite web url and pass it to SPSite constructor to get the current Site Collection object.

Instruction2: SPSite spsite2 = SPContext.Current.Site;

Process: Now we are in subsite and we are calling the above code, which directly retrives the Site Collection object. There is no looking for web url parameter to get the SiteCollection.

Result:

spsite1.RootWeb and spsite2.RootWeb returns the same Top-Level web SPWeb object.

spsite1.OpenWeb() returns the subsite (SPWeb) object if we are in subsite. spsite2.OpenWeb() returns the top-level site (SPWeb) object, even we are in subsite.

For the spsite1, we have to call dispose method to dispose the SPSite object. But for the spsite2, the sharepoint will take care on disposing of SPSite object.

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top