Check if URL is a valid SPWeb in an SPSite
Question
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?
Solution
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
}
}
}
OTHER TIPS
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
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);
}
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange