다음을 통해 공유


SharePoint 2010: How To Copy Users Between SharePoint Groups using C#

Because SharePoint does not support nesting of groups, one of the pain areas is to copy the users between two different groups.

We can use the UI (user interface)  to copy the membership of one group to another, but this is time-consuming. Another way to achieve this task is by using the code.

This article contains an example of writing a simple console application to perform the task of copying all the users from one list to another.This example code works with SharePoint 2007 and SharePoint 2010. The console application takes three input values, SiteUrl, SourceGroup and destination groups.

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();
                }
            }
        }
    }
}