I am using the System.DirectoryServices.AccountManagement part of the .Net library to interface into ActiveDirectory.
Having called GetMembers() on a GroupPrincipal object and filter the results, I now have a collection of UserPrincipal objects
GroupPrincipal myGroup; // population of this object omitted here
foreach (UserPrincipal user in myGroup.GetMembers(false).OfType<UserPrincipal>())
{
Console.WriteLine(user.SamAccountName);
}
The above code sample will print out usernames like "TestUser1". I need to compare these to a list coming from another application in "DOMAIN\TestUser1" format.
How do I get the "DOMAIN" part from the UserPrincipal object?
I can't just append a known domain name as there are multiple domains involved and I need to differentiate DOMAIN1\TestUser1 and DOMAIN2\TestUser2.
You could look for the possible domains in the user.DistinguishedName property. A user in Domain 1 should contain the string "DC=DOMAIN1". It definitely shouldn't contain the string "DC=DOMAIN2".
You have two choices that I can think of.
name@fully.qualified.domain.name
;System.DirectoryServices
namespace.I don't know about UserPrincipal, neither do I about GroupPrincipal. On the other hand, I know of a working way to achive to what you want.
Other related information or links available in this SO question.
C# Active Directory: Get domain name of user?
How to find the NetBIOS name of a domain
As mentioned in one of the comments to the question I think this is a good answer for more recent times:
Have you tried passing the fully qualified domain name to this other app? Most windows API's won't complain if you do
fully_qualified_domain\USER
.Use the ActiveDs COM library, it has built-in name translation that works and does not make any assumptions (like other answers here).