Eri*_*ric 6 .net c# active-directory
我正在使用C#objectGuid通过查询Active Directory 来查找我的本地计算机.为此,我正在使用a DirectorySearcher,将其作为搜索根传递(硬编码)路径,然后按计算机名称进行过滤:
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 + "))";
Run Code Online (Sandbox Code Playgroud)
我不想硬编码搜索根,并想知道是否有更好的方法.我想过只使用一个空的搜索根,但我担心计算机名称在不同的域中可能并不总是唯一的.
有没有更好的办法?
如果您使用的是.NET 3.5或更高版本,则可以使用a PrincipalSearcher和"按示例查询"主体进行搜索:
// 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.....
}
Run Code Online (Sandbox Code Playgroud)
如果您还没有 - 绝对阅读MSDN文章.NET Framework 3.5中的管理目录安全主体,它很好地展示了如何充分利用新功能System.DirectoryServices.AccountManagement