Question

Hello I am trying to fetch a list item and want to know if this is a good practice.

   SPSite spsite = new SPSite(SPContext.Current.Web.Url);
                    SPWeb spWeb = spsite.RootWeb;
                    SPList spList = spWeb.Lists.TryGetList("MyList");
//here is the code to fetch the values...

We have 1 site collection with 50 subsites and more subsites within them. My question is;

Suppose I am on one of the subsites under subsite number 10 and this code is executed, then will it still pickup the root web list or give error?

I am confused because the value of the SPContext.Current.Web.Url will be the current URL at respective location. Then, would the code still work?

Was it helpful?

Solution

your creating a new site that is not disposed, SPContext.Current.Web.Url only generates the string url.

correct way:

   using (SPSite spsite = new SPSite(SPContext.Current.Web.Url))
   {
        SPWeb spWeb = spsite.RootWeb;

        SPList spList = spWeb.Lists.TryGetList("MyList");
   }

there is no need to dispose of the spweb as you noted there is no new. Its using the new spsite web object. If you dispose it would lead to errors on uls:

Detected use of SPRequest for previously closed SPWeb object. Please close SPWeb objects when you are done with all objects obtained from them, but not before.

another way to use the code would be:

SPWeb spWeb = SPContext.Current.Site.RootWeb;
SPList spList = spWeb.Lists.TryGetList("MyList");

as you can see there is no need to dispose as its using the current site rootweb object that shouldnt be disposed of and less code/ system resources!

OTHER TIPS

As pointed out by @Robert, it will pickup the root web. However, you don't need to dispose SPWeb object retrieved from SPSite.RootWeb property. You can also directly get the SPSite object from SPContext SPSite spsite = SPContext.Current.Site; and hence does not not need to be disposed instead of instantiating a new one which needs to be explicitly disposed.

It will pickup the RootWeb.

But please remember to dispose the spsite when you are done, if not using a "using-statement":

spsite.Dispose()

You can use SPContext.Current.Site.Url, while creating SPSite object inside your code,then use site.OpenWeb(), which will give the root web(since SPSite object is created with Site URL). Always better to use using to disposing objects.

using (SPSite site=new SPSite(SPContext.Current.Site.Url))
            {
                using(SPWeb web=site.OpenWeb())//always gets you the root web
                {

                }
             }

See this blog about SPDisposeCheck best practice.

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