views:

438

answers:

2

How could I find out if a URL is available and usable to create a new site within a site collection or whether it is already in use by an other site, list or library?

Assumed that the relative URL "/newUrl/ is not yet in use, the following code won't actually throw an exception until you try to access any of the SPWeb's properties.

using(SPSite site = new Site("http://portal/")) 
{    
    SPWeb web = site.OpenWeb("/newUrl/"); // no exception

    string title = web.Title;  // throws exception
}

Of course it would be possible to check the availableness of the URL this way, but it would be more like a hack than like good code.

So got anyone any ideas how to solve this?

Bye, Flo

+2  A: 
if (web.Exists)

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.exists.aspx

Chris Ballance
Thank, I never thought about a such a simply solution. ;)
Flo
+4  A: 

The normal answer is

if(web.Exists)

But... you might want to wrap this SPWeb into a using.

using(SPWeb web = site.OpenWeb("/newUrl/"))
{
   if(web.Exists)
   {
       string title = web.Title;
   }
}
Maxim
+1 for evangelizing SharePoint disposal patterns :-)
LeonZandman