2009年2月7日 星期六

ADSI技術文章-使用LDAP Provider取得User的Primary Group

DirectoryEntry domain=new DirectoryEntry(ladpPath, accountName, pwd);
search.SearchScope = SearchScope.Subtree;
search.Filter = "(objectclass=User)";
SearchResult result = search.FindOne();
object primaryGroupID=result.Properties["primaryGroupID"][0];
DirectoryEntry gEntry = new DirectoryEntry(ldapRootPath,account,password);
DirectorySearcher search = new DirectorySearcher(gEntry);
search.SearchScope = SearchScope.Subtree;
search.Filter = "(objectclass=group)";
string rv = string.Empty;
try
{
SearchResultCollection result = search.FindAll();
string sid;
foreach (SearchResult sr in (IEnumerable)result)
{
sid = ObjectIdToString((byte[])sr.Properties["objectsid"][0]);
if (sid.EndsWith(primaryGroupID.ToString()) == true)
{
rv = sr.Properties["cn"][0].ToString();
break;
}
}
}
catch{
}


public string ObjectIdToString(byte[] oSid)
{
SecurityIdentifier sid = new SecurityIdentifier(oSid, 0);
return sid.ToString();
}

//重點提示:group objectSid 的尾碼==PrimaryGroupID

沒有留言: