This topic has not yet been rated - Rate this topic

SPSite.OpenWeb Method ()

Windows SharePoint Services 3
Returns the site that is associated with the URL that is used in an SPSite constructor.

Namespace: Microsoft.SharePoint
Assembly: Microsoft.SharePoint (in microsoft.sharepoint.dll)
public SPWeb OpenWeb ()

Return Value

An SPWeb object that represents the site.

When used in conjunction with an SPSite constructor, the OpenWeb method returns the lowest-level site specified by the URL that is passed as parameter for the constructor. For more information about using the OpenWeb method with an SPSite constructor, see the OpenWeb method overload.

The following code example returns the Web site that is located at http://Server_Name/sites/Site_Name/Subsite_Name.

string strUrl = 
   "http://Server_Name/sites/Site_Name/Subsite_Name/default.aspx";
using (SPSite oSiteCollection = new SPSite(strUrl))
{
    using(SPWeb oWebsite = oSiteCollection.OpenWeb())
    {
        ...
    }
}
NoteNote:

Certain objects implement the IDisposable interface, and you must avoid retaining these objects in memory after they are no longer needed. For information about good coding practices, see Best Practices: Using Disposable Windows SharePoint Services Objects.

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Use of phrase "lowest-level site" seems odd
Under the remarks section, it states: "... [the] OpenWeb method returns the lowest-level site specified by the URL ...".

Since there could be sites below the one associated with the last component of the url, wouldn't it be clearer if
the wording was something like: "... the site associated with the last component of the url" ?
Memory leak issues?

You should use using() or a finally clause on everything you instantiate that has a Close or Dispose method.

This usually doesn't indicate memory leak, it indicates that unmanaged resources are still open.

It's the job of class designers to release unmanaged resources in both the Dispose/Close and Finalize methods. Generally, if you Close/Dispose something explicitly you can suppress the finalizer from being called by the GC:

Private m_finalized As Boolean = False
Protected Overrides Sub Finalize()
Dispose()
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
If Not m_finalized Then
If m_web IsNot Nothing Then
m_web.Dispose()
End If
        m_finalized = True
GC.SuppressFinalize(Me)
End If
End Sub
Memory leak issues...

I only recently realised the following...

To avoid memory leaks, you should explicitly call the Close / Dispose method when you are finished with your SPWeb and SPSite objects. Alternatively use using structures in your code to ensure that the Dispose method is called. E.g.

using (SPSite mySite = new SPSite(url))
{
using (SPWeb myWeb = mySite.OpenWeb())
{
// Do something here ...
}
}

Edit: found this article that gives more info http://msdn2.microsoft.com/en-us/library/ms778813.aspx