More robust usage of OpenWeb()

1:  using(SPSite site = new Site(http://www.portal.com)) 
   2:  {    
   3:      SPWeb web = site.OpenWeb("/anotherWeb/"); // no exception
   4:   
   5:      string title = web.Title;  // throws exception
   6:  }

 

The first line in the using clause will not throw an exception even if anotherWeb doesn’t exist , but you’ll encounter a FileNotFoundException exception in the second line since web is a null reference.

To make your code more robust, you should check the existence of the web before using it as follows:

   1:  using(SPWeb web = site.OpenWeb("/anotherWeb/"))
   2:  {
   3:     if(web.Exists)
   4:     {
   5:         string title = web.Title;
   6:     }
   7:  }

Alternatively, The SPSite.OpenWeb method has a (string, bool) overload. If you set the bool to true you should get an exception if the site doesn’t exist. Waldek Mastykarz has explained this behavior on his blog @http://blog.mastykarz.nl/inconvenient-opening-spsite-openweb.

Advertisement

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 )

Facebook photo

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

Connecting to %s