SharePoint objects get bit tricky when it comes to check if an objects exists or not specially in SharePoint 2007. Today I came across a situation where I had to check if a web exists or not, so I tried using this code,
using (SPSite site = new SPSite("https://myPortal.myCompany.com/Sites/SubSites/DoesnotExistsSite"))
using (SPWeb web = site.OpenWeb())
{
if(web.Exists)
//Do this
}
Above code complied perfectly and didn't threw any error at all, however it didn't worked as I was expecting an error e.g. "Web doesn't exists". So I did realized you give any address to SPSite() method it will try to get site collection object regardless of full URL provided exists or not, okay it's something that might does makes sense, but when it tries to open web using OpenWeb() method, it should open the web URL has been provided to, for example this URL,
https://myPortal.myCompany.com/Sites/SubSites/DoesnotExistsSite
It will opens SubSites web, and if URL is
https://myPortal.myCompany.com/Sites/SubSites/DoesnotExistsSite/alksjdalskdjaslkdjaskldjasldjasld
It still opens up SubSites as SPWeb object.
I was expecting it to throw an error however it didn't so I got "true" for web.exists.
I did some research and figured out another way to find out if SPWeb actually exists for supplied URL or not,
I was expecting it to throw an error however it didn't so I got "true" for web.exists.
I did some research and figured out another way to find out if SPWeb actually exists for supplied URL or not,
public static void DoesWebExists()
{
string tempUrl = "https://myPortal.myCompany.com/Sites/SubSites/DoesnotExistsSite/alksjda";
string tempUrl = "https://myPortal.myCompany.com/Sites/SubSites/DoesnotExistsSite/alksjda";
Uri u = new Uri(tempUrl);
using (SPSite site = new SPSite(tempUrl))
using (SPWeb web = site.OpenWeb(u.AbsolutePath.ToString(), true))
{
Console.WriteLine(web.Exists);
}
}
Above example has been tested and works fine as far as SPSite object exists for provided Url.
Above example has been tested and works fine as far as SPSite object exists for provided Url.
In your example u.Host returns "myPortal.myCompany.com", which the SPSite contructors throws an error saying it can't understand the Uri format.
ReplyDeleteJames, I have fixed the example code, should work fine now, Thanks for pointing it out.
Delete