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.


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.


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


Conclusion

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

Advertisements

One thought on “Programmatically Fetching User Name of SharePoint site collection using Object Model

  1. Can I create “Windows Form” and use the same code and get the user list?? second question is do I have to be in the server with admin account to get the list??? I need to get the user list for around 500 site collections.. So I created a new windows form where I could input the site collection and get the user list…

    Thanks in Advance!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s