The method SPSite.Exists
checks whether the site-collection exists at the specified URL. But returns false
if the URL points to a sub web of a site collection.
Given the following structure:
http://server -> site collection
http://server/web -> sub web
http://server/sites/somesite -> site collection
SPSite.Exists(new Uri("http://server")) // returns true
SPSite.Exists(new Uri("http://server/web")) // returns false
SPSite.Exists(new Uri("http://server/sites/somesite")) // returns true
If you want to check if there is any web at the given URL you have to use the method SPSite.OpenWeb(string url, bool requireExactUrl)
:
public static bool SiteExists(string url)
{
try
{
using (SPSite site = new SPSite(url))
{
using (SPWeb web = site.OpenWeb(url, true))
{
return true;
}
}
}
catch (FileNotFoundException)
{
return false;
}
}
The SPSite
constructor takes any URL pointing to a sub element of the site-collection. Even if there is no element at the given location.
new SPSite("http://server/this/does/not/exist");
This snipped will return the site collection located at http://server.
While this is in most situations very useful there are situations where this is dangerous. Consider the following method:
public static void DeleteSite(string url)
{
new SPSite(url).Delete();
}
If this method is called with http://server/this/does/not/exist the top most site collection at http://server will be deleted.