Reputation: 6016
I'm using C# to find my local computer's objectGuid
by querying Active Directory. To do this, I'm currently using a DirectorySearcher
, passing it a (hardcoded) path as the search root, and then filtering by computer name:
string adRootPath = @"LDAP://OU=foo,DC=bar,DC=baz,DC=com";
DirectoryEntry adRoot = new DirectoryEntry(adRootPath);
DirectorySearcher searcher = new DirectorySearcher(adRoot);
searcher.Filter = @"(&(objectCategory=Computer)(CN=" + Environment.MachineName + "))";
I don't want to hardcode the search root, and was wondering if there is a better way. I thought about just using an empty search root, but I was worried that computer names may not always be unique across different domains.
Is there a better way?
Upvotes: 6
Views: 2102
Reputation: 2011
You should be able to get the domain by just calling RootDse.
This site has a good example - Site with an example of RootDSE
Upvotes: 1
Reputation: 755321
If you're on .NET 3.5 or newer, you can use a PrincipalSearcher
and a "query-by-example" principal to do your searching:
// create your domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// define a "query-by-example" principal - here, we search for a ComputerPrincipal
// and with the name of "MyPC"
ComputerPrincipal cp = new ComputerPrincipal(ctx);
cp.Name = "MyPC";
// create your principal searcher passing in the QBE principal
PrincipalSearcher srch = new PrincipalSearcher(cp);
// find all matches
foreach(var found in srch.FindAll())
{
// do whatever here - "found" is of type "Principal" - it could be user, group, computer.....
}
If you haven't already - absolutely read the MSDN article Managing Directory Security Principals in the .NET Framework 3.5 which shows nicely how to make the best use of the new features in System.DirectoryServices.AccountManagement
Upvotes: 8