0

I create a SPWeb object with a relative url to my SPSite

using (SPWeb web = SPContext.Current.Site.OpenWeb(url))
{
    SPList centralManagementList = web.Site.RootWeb.Lists["mylist"];
    string id = web.ID.ToString();
}

With this object I can create new object like a SPList (no errors)

When i access the ID of the SPWeb object, i get the error, that the site does not exists?! But it does - I tried relative to the SPSite and relative to the SPServer.

What's wrong?

1

The url can be either SPSite relative (not starting with /)
Or Server Relative (starting with /)
But it has to be a subsite of the SPSite you start with

Usually I use a full url and do it like this:

using (SPSite site = new SPSite(url)) 
  using (SPWeb web = site.OpenWeb()) 
  { 
    SPList centralManagementList = web.Lists["mylist"]; 
    string id = web.ID.ToString(); 
  } 
}

then you're sure to get the right SPSite and SPWeb

Note that in your code you're refering to web.Site.RootWeb when using the List
web.Site.RootWeb will be valid even if web.Exists is false as it knows which SPSite you're refering to from the OpenWeb call even though it didn't allocate a fullblown SPWeb

  • Thank you, that's it! Additional I use now SPContext.Current.Site.MakeFullUrl(url) before. – Sebastian Apr 4 '12 at 13:37
0

Try to use this method

public SPWeb OpenWeb(
    string strUrl,
    bool requireExactUrl
)

Like this

using (SPWeb web = SPContext.Current.Site.OpenWeb(url, true))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.