Programmatically Fetching User Name of SharePoint site collection using Object Model


Objective:

In this article, I will show you how to fetch all the user name of a SharePoint site collection using program or Visual Studio.

Step1:

Create a SharePoint site and add few users in that by configuring the site in SharePoint. I have created a site called "Document Center" and added few users in that.

The site with user is as below image.

image1.gif

Step2:

Create a new project in Visual studio. Select any type for the project. I am choosing the project type as a Console Application. So to create new console application project, select New->Project->Console Application.

Step 3:

Add the assemblies (dll) required to access SharePoint site. To add assemblies click on Reference in solution Explorer then selects Add Reference and adds below assemblies.

image2.gif

Now you would able to see,

Microsoft.SharePoint dll in reference list of your project.

Step 4:

Add the namespace

using Microsoft.SharePoint;

Step 5:
 
Create Instance of SPSite

SPSite spsite = new SPSite("http://adfsaccount:2222/");

I am passing root site URL in constructor. We will get all the sites inside this site collection specified by URL.
So now spsite is a site collection.

Step 6:

Take collection of sites in site collection using SPWeb

SPWeb web=  spsite.RootWeb;

Step 7:

Take all the users in SPUserCollection

SPUserCollection  userlist=  web.AllUsers;

So, the entire code to fetch the user name in Console application is as follows

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            SPSite spsite = new SPSite("http://adfsaccount:2222/");
            SPWeb web=  spsite.RootWeb;
            SPUserCollection  userlist=  web.AllUsers;
            foreach (SPUser u in userlist)
            {
                Console.WriteLine(u.Name);
            }
            Console.Read();
        }
    }
}

Output

image3.gif

Conclusion:

In this article, I showed how to fetch the entire user name programmatically from a SharePoint site collection. Thanks for reading.

Happy Coding

Up Next
    Ebook Download
    View all
    Learn
    View all