tags:

views:

92

answers:

1

When I want to get to a web, I usually have to do code like the following which is fairly self explanatory.

using (SPSite site = new SPSite(siteUrl))
            {
                SPWeb web = null;

                if (string.IsNullOrEmpty(webName))
                    web = site.RootWeb;
                else
                    web = site.AllWebs[webName];
                ...
                web.Close();
            }

Given a url that points directly to a web:

So in this case siteUrl would be: http://localhost/sites/testsite

and webName would be: testWeb

I would like to simply get a single bit of information from the user opposed to these two seperate bits, ie the url directly to the web: http://localhost/sites/testsite/testweb/

I would like to use this url to open the web and not have to specify the web name manually. I've played with site.OpenWeb and tried passing the url to this too but it doesn't like that. It only wants a server relative url. Is there a way to just be able to get a single url from the user in order to open the web, short of pulling the url apart and making assumptions that the last bit may or may not be the name of the web depending on whether we're going to the root web or not but then that makes the code even worse.

+6  A: 

You don't need split the absolute SPWeb URL to access the SPWeb. You can simply do the following.

using (SPSite site = new SPSite(<url to spweb>))
{
      using(SPWeb web = site.OpenWeb())
      {
         // put your code here ...
      }
}
Flo
What a stupid thing for me not to know. It says it right there in the documentation. I had it in my head that the default constructor opened the root web. Must have been misinformation at some point. Well thanks for clearing me up on this.
Dan Revell
No, problem. You're welcome.
Flo