我需要从 C#.net 中的 SharePoint 网站集中删除用户。这是 powershell 代码的链接,但我需要用 C# 编写。 https://learn.microsoft.com/en-us/sharepoint/remove-users
以下代码不起作用。
private void RemoveUser(String user)
{
using (SPSite sps = new SPSite("http://serverName"))
{
using (SPWeb spWeb = sps.RootWeb)
{
SPUserCollection spuc = sps.RootWeb.AllUsers;
spuc.Remove(user);
}
}
}
我有一个名为 sridemosite 的 SharePoint 网站,其成员如下:
来自 SharePoint 管理中心:
来自 SharePoint 门户:
要从 .NET 中的此 SharePoint 网站集中删除用户,我使用了以下代码:
using System;
using System.Linq;
using System.Security;
using Microsoft.SharePoint.Client;
namespace CSOMAuthentication
{
class Program
{
static void Main(string[] args)
{
// Provide Site URL
string SiteURL = "https://xxxxxxxxxxx.sharepoint.com/sites/sridemosite";
string Environmentvalue = "o365";
string username = "[email protected]";
string password = "xxxxxxxxxxx";
AuthenticateUser(new Uri(SiteURL), Environmentvalue, username, password);
}
private static void AuthenticateUser(Uri TargetSiteUrl, string Environmentvalue, string username, string password)
{
try
{
// Based on the environmentvalue provided it execute the function.
if (string.Compare(Environmentvalue, "o365", StringComparison.OrdinalIgnoreCase) == 0)
{
ClientContext Context = O365LogOn(username, password, TargetSiteUrl);
Group oGroup = Context.Web.SiteGroups.GetByName("sridemosite Members");
// Get user using Logon name
User oUser = Context.Web.EnsureUser("[email protected]");
Context.Load(oUser);
Context.ExecuteQuery();
// Remove user from the group
oGroup.Users.RemoveByLoginName(oUser.LoginName);
Context.ExecuteQuery();
}
}
catch (Exception ex)
{
// log error
}
}
private static ClientContext O365LogOn(string userName, string password, Uri url)
{
ClientContext clientContext = null;
ClientContext ctx = null;
try
{
clientContext = new ClientContext(url);
// Condition to check whether the user name is null or empty.
if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
{
SecureString securestring = new SecureString();
password.ToCharArray().ToList().ForEach(s => securestring.AppendChar(s));
clientContext.Credentials = new SharePointOnlineCredentials(userName, securestring);
clientContext.ExecuteQuery();
}
else
{
clientContext.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
clientContext.ExecuteQuery();
}
ctx = clientContext;
}
finally
{
if (clientContext != null)
{
clientContext.Dispose();
}
}
return ctx;
}
}
}
回复:
为了确认,我在两个门户中检查了相同的内容,其中
Devi
用户已成功从网站集中删除,如下所示:
来自 SharePoint 管理中心:
来自 SharePoint 门户:
参考资料: