tags:

views:

1273

answers:

3

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") ;
+3  A: 
SPSite spSite = new SPSite("http://myurl");
SPWeb spMySite = spSite.Allwebs["mysite"];
SPWeb spRootsite = spsite.RootWeb;

The console app will only run on the server as usual. Also, the url used http://myurl can be a url to a page and an SPSite object will be created. E.g. http://myurl/mysite/pages/default.aspx will get a valid SPSite object.

Nat
Just make sure you take into account what Nico stated, SPSite and SPWeb both implement IDisposable and you really need to dispose of then when you're done. http://blogs.msdn.com/rogerla/archive/2008/02/12/sharepoint-2007-and-wss-3-0-dispose-patterns-by-example.aspx for more on that
Slace
Yeah, nothing like leaving 2MB objects just lying around.
Nat
Thanks again for this response. I came back to this again today for reference.
Peter Walke
+6  A: 

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.

Nico
A: 

There are a couple of other ways you can use SPSite.OpenWeb() as well...

If you keep track of the SPWeb object's GUID:

site.OpenWeb(webUid);

Using a web's server or site relative URL or title, see MSDN SPSite.OpenWeb(string) for more details:

site.OpenWeb(relativeUrl);
site.OpenWeb(title);

Using the precise relative URL and avoiding any clever stuff that SPSite.OpenWeb(string) uses:

site.OpenWeb(relativeUrl, true);
Alex Angas