I am trying to retrieve all the email gruops and their mail address from company's AD system. I've got about 1800 groups but I've found there are about 20 gourps which I cannot get their properties. I tried in my outlook and got properties like mail address correctly. But I cannot get them by code, someone please help. Thanks. Below is my code snippet:
static void TestGroupEmails()
{
ICollection<DirectoryEntry> groups = GetGroups();
Console.WriteLine(groups.Count + "groups");
List<String> noNameGroups = new List<String>();
foreach (DirectoryEntry de in groups)
{
String name = de.Properties["sAMAccountName"].Value as String;
String email = de.Properties["mail"].Value as String;
if (String.IsNullOrEmpty(email))
noNameGroup开发者_JAVA百科s.Add(name);
}
StreamWriter writer = new StreamWriter(@"C:\ad\group mails.txt");
noNameGroups.Sort();
foreach (String name in noNameGroups)
{
writer.WriteLine(name);
}
writer.Close();
Console.ReadLine();
}
public static List<DirectoryEntry> GetGroups()
{
String filter = @"(&(objectCategory=group))";
List<DirectoryEntry> groups = new List<DirectoryEntry>();
using (DirectoryEntry root = new DirectoryEntry(Constants.ADConnPrefix))
{
using (DirectorySearcher searcher = new DirectorySearcher(filter, null))
{
searcher.PageSize = 10000;
searcher.ReferralChasing = ReferralChasingOption.All;
searcher.SearchScope = SearchScope.Subtree;
searcher.SearchRoot = root;
root.Username = Constants.UserName;
root.Password = Constants.Password;
using (SearchResultCollection searchResult = searcher.FindAll())
{
foreach (SearchResult sr in searchResult)
{
DirectoryEntry de = sr.GetDirectoryEntry();
groups.Add(de);
}
}
}
}
return groups;
}
public static SearchResult GetGroupInfo(String groupName)
{
String normalName = Utility.RemoveLoginNamePrefix(groupName);
String filterFormat = "(&(objectCategory=group)(sAMAccountName={0}))";
using (SearchResultCollection searchResult = Search(ADConnPrefix, null, filterFormat, normalName))
{
int count = searchResult.Count;
SearchResult sr = searchResult[0];
return sr;
}
}
Are you certain the groups in question actually have email addresses? It is possible for groups in AD to not have them.
If you modify your search filter to (&(objectCategory=group)(mail=*))
it will filter out any groups that don't have email addresses.
精彩评论