Check whether a website exists in a site collection

The easiest way I found is

// Checks whether a website exists by looking up its url in the current site collection
bool WebExistsByUrl(string url)
{
return SPContext.Current.Site.AllWebs.Any(w => w.Url.Equals(url, System.StringComparison.InvariantCultureIgnoreCase));
}

// Checks whether a website exists by looking up its name in the current site collection
public static bool WebsiteExistsByName(string name)
{
return Array.Exists(SPContext.Current.Site.AllWebs.Names, n => n == name);
}

or even better you can put them in an extension class to be more accessible:

public static class SiteExtensions
{
    // Checks whether a website exists by looking up its name
    public static bool WebExistsByName(this SPSite site, string name)
    {
        return Array.Exists(site.AllWebs.Names, n => n == name);
    }

    // Checks whether a website exists by looking up its URL
    public static bool WebExistsByUrl(this SPSite site, string url)
    {
        return site.AllWebs.Any(w => w.Url.Equals(url, StringComparison.InvariantCultureIgnoreCase));
    }
}
Advertisements
Check whether a website exists in a site collection

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s