【问题标题】:How to get a list of all users from Office 365 Organization in C# using CSOM?如何使用 CSOM 从 C# 中的 Office 365 组织中获取所有用户的列表?
【发布时间】:2020-01-06 16:05:37
【问题描述】:

我的 Office 365 组织中有 4000 多个用户,我希望使用 CSOM 将所有这些用户添加到我的 C# 中的 SharePoint 子网站。我知道我可以使用 PowerShell 代码来实现这一点,但我想使用 CSOM 在 C# 中做到这一点。我可以通过以下代码添加特定用户,但是如何在一个代码中添加所有 4000 多个用户?有没有办法在一个包含所有 4000 多个用户的循环中迭代一个对象?

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

【问题讨论】:

    标签: c# .net sharepoint office365 csom


    【解决方案1】:

    请参考 this project 注册您的应用,以便您可以调用 graph api 从 AD 获取用户。

    if (graphServiceClient != null)
                    {
                        var users= await graphServiceClient.Users.Request().GetAsync();
    

    将用户添加到 SharePoint 时,建议执行此批处理(一次请求提交 100 个用户以避免问题)。

    假码:

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

    【讨论】:

      【解决方案2】:

      如果您的组织有 AD(我相信是这样),您可以使用它

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

      【讨论】:

      • 此代码显示来自特定组的用户,而不是组织中的所有用户。我需要显示组织的所有用户名。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多