Wednesday, April 15, 2009

How to open SPSite, SPWeb in ASP.NET

This small article will describe , how to open SPSite and SPWeb from asp.net application and how to dispose it properly.

Since we are required to open a sharepoint object, so we need to refer Microsoft.Sharepoint.dll.
The location of the dll is:
Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI

Step 1. : Refer the above dll and add the namespace:
using Microsoft.Sharepoint; //C# code written

Step 2:
SPSite is an object to create an instance of a Sharepoint Site
SPWeb is an object to create an instance of a Sharepoint Web.

using (SPSite ospSite=new SPSite ("http://servername:portname"))
{
using (SPWeb ospWeb=ospSite.openWeb())
{
//At this point you can perform any operation on ospWeb and ospSite.
}
}

Here, I have used using to open an instance of SPSite/SPWeb object because this automatically dispose the object as the scope ends.
You don't required to close and dispose it again.
For more detials, check the following link:

http://firstblogofvarun.blogspot.com/2009/03/disposing-spweb-and-spsite-objects.html

4 comments:

Anonymous said...

Varun,
Can i use spweb in asp.net on machine not having sharepoint server

Varun Sharma said...

Yes..why not..
It may be the case that the Sharepoint is installed on the production server and from development enviornment , you are developing the code.

By writing this line:
using (SPSite ospSite=new SPSite ("http://servername:portname"))

creates an instance of SPSite referring to site : http://servername:portname

SO from that you can also refer to SPWeb.

In your development PC, you need to add reference to Sharepoint dlls.

Thats all

Cheers
Varun

Anonymous said...

Hi Varun,
Thanks for instant reply, really apreciate that.

Manikandan said...

Hi Varun,
where do i get the Microsoft.Sharepoint.dll. i am not able to find these dll inside Program Files\Common Files\Microsoft Shared\web server extensions\15\ISAPI