Opening the current SPWeb

I used to open the current SPWeb like so:

  using (SPSite site = new SPSite(SPContext.Current.Web.Url))
        {
            using (SPWeb web = site.OpenWeb())
            {


            }
        }



However, if you access a SharePoint site with a URL that isn't in the alternate access mappings of the server, then the above code will create an error.


File Not Found.   at Microsoft.SharePoint.SPSite..ctor(SPFarm farm, Uri requestUri, Boolean contextSite, SPUserToken userToken)
   at Microsoft.SharePoint.SPSite..ctor(String requestUrl)
   at wdCalendar_Services_GenerateSampleData.Page_Load(Object sender, EventArgs e)
   at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
   at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
   at System.Web.UI.Control.OnLoad(EventArgs e)
   at System.Web.UI.Control.LoadRecursive()
   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
Troubleshoot issues with Windows SharePoint Services.


OR

if you try catch it:

The Web application at http://[invalid aam site] could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application.


To avoid this error, you can get the default site and web by using the ID instead of the URL:

  using (SPSite site = new SPSite(SPContext.Current.Site.ID))
        {
            using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
            {


            }
        }

Comments

Popular posts from this blog

How To use ASPNET_SetReg to store encrypted data in the registry and then decrypt the data for use in your app

Nostalgia for SNL's Il Returno De Hercules

PowerShell Script to Clean the Windows Installer Directory