Showing posts with label Active Directory. Show all posts
Showing posts with label Active Directory. Show all posts

Tuesday, August 24, 2010

Add Active Directory Users to SharePoint Group

string loginName = null;


string loginEmail = null;

SPSite thisSite = null;

SPWeb thisWeb = null;

SPGroup thisGroup = null;

DirectoryEntry user = null;



DirectoryEntry directoryEntry = new DirectoryEntry(ldap://yourdomain/);

DirectorySearcher ds = new DirectorySearcher(directoryEntry);

ds.Filter = "(&(objectClass=group)(cn=yourgroup))";



object groupMembers = ds.FindOne().GetDirectoryEntry().Invoke("Members", null);

foreach (object groupMember in (IEnumerable)groupMembers)

{

user = new DirectoryEntry(groupMember);

if (!(user.Properties["sAMAccountName"].Value == null))

{

loginName = user.Properties["sAMAccountName"].Value.ToString();

}



if (!(user.Properties["mail"].Value == null))

{

loginEmail = user.Properties["mail"].Value.ToString();

}



string userName = user.Name.Remove(0, 3).Replace("\\", "");





thisSite = new SPSite("http://yoursite");

thisWeb = thisSite.OpenWeb();

thisGroup = thisWeb.SiteGroups["yourgroup"];

try

{



if (thisGroup.Users["yourdomain\\" + loginName].LoginName.ToString() == loginName) { }

}

catch

{

thisGroup.AddUser("yourdomain" + loginName, loginEmail, userName, "Added by System.");

}

}

thisWeb.Dispose();

thisSite.Dispose();

user.Dispose();

ds.Dispose();