Thursday, May 24, 2012

List all site owners in a site collection programmatically



The following code is a simple code to get all site owners from the site collection. Execute the following code as a console application

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

namespace MyPortal
{
    class ListAllSiteOwners
    {
     
        static void Main(string[] args)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {

                FileStream ostrm;
                StreamWriter writer;
                TextWriter oldOut = Console.Out;
                try
                {
                    ostrm = new FileStream("./SiteOwners.txt", FileMode.OpenOrCreate, FileAccess.Write);
                    writer = new StreamWriter(ostrm);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Cannot open  SiteOwners.txt for writing");
                    Console.WriteLine(e.Message);
                    return;
                }
                Console.SetOut(writer);

             
                using (SPSite site = new SPSite(args[0]))
             
                    foreach(SPWeb web in site.AllWebs)
                    {
                        //SPUserCollection allAdmins = web.AssociatedOwnerGroup;
                        SPGroup ownerGroup = web.AssociatedOwnerGroup;
                        if (ownerGroup != null)
                        {

                            foreach (SPUser user in ownerGroup.Users)
                            {
                                Console.WriteLine(web.Url +"\t"+ ownerGroup.Name + "\t" + user.Name);
                            }
                        }
                        web.Dispose();
                    }
             
                Console.SetOut(oldOut);
                writer.Close();
                ostrm.Close();
            });
        }
    }
}

After the code is built, you need to execute the  ListAllSiteOwners.exe from the command prompt with site collection URL as argument. 

D:\> ListAllSiteOwners http://yoursitecollectionURL

You will find the  SiteOwners.txt  file in the same location where the exe is placed. Copy the content from the text to excel for better view.

No comments:

Post a Comment