[英]How to connect to SharePoint on Office 365 with CSOM from C#?
[英]How to get a list of all users from Office 365 Organization in C# using CSOM?
我的 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();
如果您的組織有廣告,您可以使用它(我相信是這樣)
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();
}
請參考此項目注冊您的應用程序,以便您可以調用圖形 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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.