Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I have a URL and I want to check if it exists as sub-site for a given URL.

  • I have a URL = www.go.com
  • I want to check if = www.go.com has URL = www.go.com/abx or not

I have +1000 sub webs, do I have to loop them all, no shortcut?

share|improve this question
    
Are you using Server side code or client side code? –  Unnie Jul 3 at 14:55
    
server side code –  Customized Name Jul 3 at 15:13
add comment

3 Answers 3

You can go with what Supermode and Unnie have suggested, you may also choose to use the below code as well:

using (SPSite site = new SPSite("http://www.go.com/"))    
{    
        using (SPWeb oWeb= site.OpenWeb())
        {
            SPWeb IsWebExists = oWeb.Webs.FirstOrDefault(x => x.Name == "abx");
            if (IsWebExists == null)
            {
                  //Your Code
            }
        }
}
share|improve this answer
add comment

Try below code:

using (SPSite site = new SPSite("http://www.go.com/"))
{
  using (SPWeb web = site.OpenWeb("abx"))
  {
     if (web.Exists)
         Console.WriteLine("exists");
     else
         Console.WriteLine("not exists");

  }
}

Just make sure inside site.OpenWeb, you provide the site relative url of the web

share|improve this answer
    
it no working// –  Customized Name Jul 3 at 15:37
    
@CustomizedName what is the url you gave in site.OpenWeb()? –  Unnie Jul 3 at 15:38
    
exactly this no work; please test and confirm if it does –  Customized Name Jul 3 at 15:40
    
i have tested in a console app in my machine. Just make sure the urls are correct –  Unnie Jul 3 at 15:43
    
You might want to try the OpenWeb(string, bool) overload and setting the bool parameter to true. By default if the specified URL doesn't exist, SharePoint will open the parent site. If you set the second parameter to true, it will explicitly check for the existence of a web at the specified URL and web.Exists will return false if the site doesn't exist. –  Waldek Mastykarz Jul 3 at 17:36
add comment

You can try the following

string serverUrl = "http://myserver";
string siteUrl = "/sites/SiteCollection";
string subSiteUrl = "This Subsite Does Not Exist";
using (SPSite site = new SPSite(serverUrl + siteUrl))
{
    using (SPWeb web = site.OpenWeb(subSiteUrl))
    {
        if (web.Exists)
        {
            // do work with the web...
            Console.WriteLine(site.Url);
            Console.WriteLine(web.Url);
        }
    }
}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.