Saturday, February 19, 2011

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

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") ;
From stackoverflow
  • 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.

    Slace : 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
    Nat : Yeah, nothing like leaving 2MB objects just lying around.
    Peter Walke : Thanks again for this response. I came back to this again today for reference.
  • 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.

  • 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);
    

0 comments:

Post a Comment