I've 4000+ users in my Office 365 organization and want to add all those users to my SharePoint subsite in C# using CSOM. I know I can I achieve this using PowerShell Codes, but I want to do it in C# using CSOM. I can add a particular user by the following code, but how to add all 4000+ users in a single code?. Is there any way to iterate a object in a loop which has all 4000+ users in it?
using System;
using System.Security;
using Microsoft.Online.SharePoint.TenantAdministration;
using Microsoft.SharePoint.Client;
namespace Basic_Site_Subsite_Group_User_Creation
{
class Program
{
static void Main(string[] args)
{
//Opens the Admin URL
using (ClientContext ctx = new ClientContext("https://developer19.sharepoint.com/sites/Created_with_Communication_site"))
{
//Authenticating with Tenant Admin
SecureString password = new SecureString();
foreach (char c in "password".ToCharArray())
password.AppendChar(c);
ctx.Credentials = new SharePointOnlineCredentials("kailash@kailash.cf", password);
Group gru = ctx.Web.SiteGroups.GetByName("subsite1");
User use = ctx.Web.EnsureUser("anil@kailash.cf");
gru.Users.AddUser(use);
ctx.ExecuteQuery();
You can use this if your organisation have a AD(I believe so)
string groupName = "Domain Users";
string domainName = "your domainName";
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName);
GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, groupName);
if (grp != null)
{
foreach (Principal p in grp.GetMembers(false))
{
p.DisplayName //do your action here
}
grp.Dispose();
ctx.Dispose();
}
Referthis project to register your app so you could call graph api to get users from AD.
if (graphServiceClient != null)
{
var users= await graphServiceClient.Users.Request().GetAsync();
When adding the users to SharePoint, would suggest do this batch(submit 100 users in one request to avoid issue).
Fake code:
for(var i = 1; i <= users.Count; i++)
{
User use = ctx.Web.EnsureUser(users[i].Mail);
gru.Users.AddUser(use);
if (i % 100 == 0)
{
ctx.ExecuteQuery();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.