Wednesday 4 April 2012

How to copy users between sharepoint groups in Sharepoint using C#

Hi,
One of the pain areas in sharepoint is to copy the users between the groups. The sharepoint does not support nesting of groups. The problem get worsen when you have huge number of users. To resolve this I have written this tool. This works in both versions of sharepoint MOSS 2007 and SPS 2010. This tool takes three input vales
1. Site Url
2. Name of the source sharepoint group (Case Sensitive).
3. Name of the destination sharepoint group (Case Sensitive).

The code for this tool is as below:

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

namespace CopyUsersBetweenGroupsInSharepointByRR
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("This tool will copy the users from one group to another group");
            Console.WriteLine("Please enter the URL of the site where your groups are available");
            String siteUrl = Console.ReadLine();
            using (SPSite site = new SPSite(siteUrl))
            {
                try
                {
                    SPWeb web = site.OpenWeb();
                    Console.WriteLine("Please enter the name of the source group");
                    String sourceGroupName = Console.ReadLine();
                    Console.WriteLine("Please enter the name of the destination group");
                    String destinationGroupName = Console.ReadLine();
                    SPGroup sourceGroup = web.Groups[sourceGroupName];
                    SPGroup destinationGroup = web.Groups[destinationGroupName];
                    SPUserCollection sourceUsers = sourceGroup.Users;
                    SPUserInfo[] sourceUserInfoArray = new SPUserInfo[sourceUsers.Count];
                    for (int i = 0; i < sourceUsers.Count; i++)
                    {
                        sourceUserInfoArray[i] = new SPUserInfo();
                        sourceUserInfoArray[i].LoginName = sourceUsers[i].LoginName;
                        sourceUserInfoArray[i].Name = sourceUsers[i].Name;
                    }
                    destinationGroup.Users.AddCollection(sourceUserInfoArray);
                    destinationGroup.Update();
                    web.Update();
                    Console.WriteLine("Operation Completed Successfully");
                    Console.ReadLine();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    Console.ReadLine();
                }
            }
        }
    }
}

I hope this will help you out.

Thanks,
Rahul Rashu

No comments:

Post a Comment