Getting Sharepoint Site/Web Context in a Console Application

I had recently faced a problem which I believe other people will face at least once: how to get the context from a URL in a C# Console Application. I needed to use ProfileLoader which requires a context. You cannot get current context when you run an application outside a Sharepoint page (like in Windows or Console Application). The solution below gets a context from the topology (which happens to be deprecated but works) and get all properties from the profile. See the sample code below:


using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.Office.Server;
using Microsoft.SharePoint.Portal;
using Microsoft.SharePoint.Portal.Topology;
using Microsoft.SharePoint;
using System.Web;

namespace TestProperties
    class Program
        static void Main(string[] args)
            //get portal site context from topology
            string strUrl = "
            TopologyManager tm = new TopologyManager();
            PortalSite ps = tm.PortalSites[new Uri(strUrl)];
            PortalContext pc = PortalApplication.GetContext(ps);
            ServerContext sc = pc.ServerContext;

            PropertyCollection props = ProfileLoader.GetProfileLoader(sc).GetUserProfileManager().Properties;

            foreach (Property prop in props)
                if (prop.Type != PropertyDataType.Binary && prop.DefaultPrivacy == Privacy.Public)
                    Console.WriteLine("{0} - {1}", prop.DisplayName, prop.Name);


Comments (3)

  1. Georgi says:

    Hi Rodney,

    You don’t need to use deprecated objects, just look in Sharepoint SDK ( and you will find code with same functionality.

    Happy coding,


  2. Hi Georgi,

    Even better. Thanks for the feedback.

Skip to main content