How do you instantiate a SPWeb Object from a console app?

Peter Walke picture Peter Walke · Nov 14, 2008 · Viewed 7.2k times · Source

I am trying to write a console app that simply lists the number of lists at the sharepoint root.

I tried doing it by using the following code, but the object SPContext.Current is null. Any ideas of how to get the web object?

 SPWeb web = SPContext.Current.Site.OpenWeb("http://localhost") ;

Answer

Nico picture Nico · Nov 14, 2008

Just adding a little thing to Nat's post:
Even if it's not a important as in a SharePoint WebApp, it's still recommenced to dispose all SPWeb and SPSite objets.
So do keep good habits:

using (SPSite site = new SPSite(weburl))
{
    using (SPWeb web = site.OpenWeb())
    {
        // bla bla
    }
}

Note: you can directly pass the weburl to SPSite constructor, so OpenWeb will open the given web.