开发者

How to get Domain from GroupPrincipal?

I need to list all users from the specific local group in the following format: "Domain\UserName". I can extract collection of GroupPrincipal objects for the group, but I don't know how to get users in required format. GroupPrincipal doesn't have property Domain.

The following code outputs users without domain (e.g. "UserName").

using (var context = new PrincipalContext(ContextType.Machine, null))
{
    using (var group = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, @"My Local Group"))
    {
        if (group != null)
        {
            foreach (var p in group.GetMembers(false))
            {
                Console.WriteLine(p.SamAccountName);
            }
  开发者_如何学运维      }
    }
}

Is it possible to get domain netbios name from the principal object? And if so, how to get it?


You can get the domain details from the principal's Context. e.g.:

foreach (var p in group.GetMembers(false))

    {
        Console.Write(p.SamAccountName);
        if (p.ContextType == ContextType.Domain)
        {
            Console.Write(" ({0})", p.Context.Name);
        }

        Console.WriteLine();
    }

If you just want to output account names in the "domain\user" format from a machine on the domain, you can translate the principal's SecurityIdentifier to an NTAccount. e.g.:

foreach (var p in group.GetMembers(false))
{
    Console.WriteLine(p.Sid.Translate(typeof(NTAccount)).ToString());
}


On a pure LDAP, the way to retreive the Netbios Name of a domain partition is the following (given that I'am working on the DC=dom,dc=fr partition) :

/* Connection to Active Directory
 */
DirectoryEntry deConf = new DirectoryEntry("LDAP://WM2008R2ENT:389/CN=Partitions,CN=Configuration,DC=dom,DC=fr", "user", "password");

/* Directory Search
 */
DirectorySearcher dsLookForNetb = new DirectorySearcher(deConf);
dsLookForNetb.Filter = "(nCName=dc=dom,dc=fr)";
dsLookForNetb.SearchScope = SearchScope.Subtree;
dsLookForNetb.PropertiesToLoad.Add("nETBIOSName");

SearchResult RefObj = dsLookForNetb.FindOne();

Console.WriteLine(RefObj.Properties["nETBIOSName"][0]);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜