Reputation: 11
I'm developing a tool in C# using the Microsoft.SharePoint.Client library to interact with SharePoint. My goal is to add a new user to a SharePoint folder and assign them specific permissions programmatically.
The problem:
When I try to add a user via the SharePoint UI using the "Share" feature, it works perfectly fine — the email gets invited as a new user. However, when I attempt the same via code, I get the following errors:
// Loading the folder by URL
Folder AccountFolder = AVIFolder.Folders.GetByUrl(Uri.EscapeDataString(FolderName));
Client.Load(AccountFolder);
Client.ExecuteQuery();
// Loading folder properties
ListItem AllFields = AccountFolder.ListItemAllFields;
Client.Load(AllFields);
Client.ExecuteQuery();
// Creating the new user
UserCreationInformation newUser = new UserCreationInformation
{
LoginName = EMail, // Using the email as LoginName
Email = EMail,
Title = "New User"
};
User user = Client.Web.SiteUsers.Add(newUser);
Client.Load(user);
Client.ExecuteQuery();
// Ensuring the user exists on the site (throws error if not)
Principal AccountUser = Client.Web.EnsureUser(EMail);
Client.Load(AccountUser);
Client.ExecuteQuery();
// Assigning specific permissions to the folder for the user
RoleAssignmentCollection RoleAssignments = AllFields.RoleAssignments;
Client.Load(RoleAssignments);
Client.ExecuteQuery();
RoleDefinitionBindingCollection collRDB = new RoleDefinitionBindingCollection(Client);
RoleDefinition ContributeRoleDef = Client.Web.RoleDefinitions.GetByType(RoleType.Editor);
collRDB.Add(ContributeRoleDef);
// Breaking role inheritance and adding role assignments
AllFields.BreakRoleInheritance(false, true);
RoleAssignments.Add(AccountUser, collRDB);
AccountFolder.Update();
Client.ExecuteQuery();
What I've tried:
Question: Is there a way to programmatically invite a new user by email to SharePoint and grant specific permissions? Or do I need to make sure the user already exists in the SharePoint site before assigning permissions?
Any help or insights on how to fix or improve this approach would be appreciated!
Thanks in advance!
Upvotes: 0
Views: 113
Reputation: 1
It's possible to add/invite users via the Graph API, however, it will require the user to first activate their account before permissions can be modified since the user isn't created until the invitation is accepted.
You could create a script to maintain a list of invited users that checks periodically if they exist and if they do, assigns permissions.
Upvotes: 0