Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open an SPWeb from a single Url

Tags:

sharepoint

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.

like image 993
Daniel Revell Avatar asked Mar 31 '10 15:03

Daniel Revell


1 Answers

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 ...
      }
}
like image 115
Flo Avatar answered Oct 12 '22 11:10

Flo