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?
If you’re on .NET 3.5 or newer, you can use a
PrincipalSearcherand a “query-by-example” principal to do your searching: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