4

I am currently running the following code to check if there is a site with a title equal to my string myname.

This code is however very time consuming because I have a large number of sites. Is there a more efficient method to test this, without using SPWeb.Exists because I am working Client Side.

using (ClientContext context = new ClientContext(spUri))
{
   context.Credentials = CredentialCache.DefaultNetworkCredentials;
   Web web = context.Web;
   context.Load(web, w => w.Title, w => w.Webs);
   context.ExecuteQuery();
   int j = 0;

   do
   {
       if (web.Webs[j].Title == myname) exists = true;
       j++;
   } while (!exists || j++ != web.Webs.Count);
}
  • 1
    Is finding your subsite by title a requirement? Can't you use the site URL ? – MdMazzotti Jan 17 '14 at 13:41
  • Site URL would be an acceptable workaround. – Martijn Burger Jan 17 '14 at 13:45
5

You can use linq query:

    var subWeb = (from w in web.Webs where w.Title == YourTitle select w).SingleOrDefault();
    if (subWeb != null)
    {
      // if found true
      return true;
    }

See more at: http://www.daniellewis.me.uk/2013/10/02/a-quick-way-to-check-if-a-sub-site-exists-using-the-sharepoint-2013-net-client-side-object-model-csom/#sthash.z7ebixoz.dpuf

  • 1
    I think the expensive call is the actual query to get the webs list – MdMazzotti Jan 17 '14 at 15:04
  • 2
    You are right. He needs a way to perform it in CSOM and not server side. So he can use the sample I provided and compare it with the one he already has to see if there is any performance gain. – Nadeem Yousuf Jan 17 '14 at 15:09
  • Huge performance gain. Thanks a million for this! @MdMazzotti The expensive call is the do - while loop. If it's the last match has 200k iterations. Linq is much more efficient. – Martijn Burger Jan 17 '14 at 16:17
  • @MartijnBurger thanks for the info! It can come in handy – MdMazzotti Jan 17 '14 at 16:26
2

You can use the WebClient class to check if the specified URL exists. Example:

using(var client = new WebClient()) {       
    try{
        string check = client.DownloadString("http://siteroot/urlSubSiteUrl");
    }
    catch(Exception ex){    
       //if you get here the site doesn't exist
    }
}

Source and more info: stackoverflow

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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