How to get from DirectoryEntry to SPuser
-
28-09-2020 - |
Question
I need to get the SPuser for a partcular directory entry.
What I need to do is get all the users from an AD group and give them permissions to a list item. The code is:
SearchResult result = mySearcher.FindOne();
DirectoryEntry myDirectoryEntry = result.GetDirectoryEntry();
Solution
You can get username Domain name from DirectoryEntry. https://stackoverflow.com/questions/941002/how-can-i-get-domain-user-from-an-ad-directoryentry
After you get the domainname you can get SPUser object as :
SPUser user = SPWeb.EnsureUser(loginName);
OTHER TIPS
The following should help:
var domainName = "<yourdomainname>";
var completeAccountName = "";
var accountName = myDirectoryEntry.Properties.Contains("samaccountname")
? Convert.ToString(myDirectoryEntry.Properties["samaccountname"][0])
: string.Empty,
// The Active Directory returns account name without domain name.
if (!accountName.StartsWith(domainName))
{ completeAccountName = domainName + "\\" + accountName; }
SPUser user = SPWeb.EnsureUser(completeAccountName);
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange