当我使用dsa.msc手动搜索计算机并打开其属性时,有一个"位置"选项卡.它可能有也可能没有价值.当我尝试使用.Net的目录服务获取此信息时,我没有看到"位置"属性.我打印出所有可用的属性,但没有看到它.它是不可用还是我错过了什么?这是部分代码:
string sADPath = "LDAP://blah.blah.com"; DirectoryEntry de = new DirectoryEntry(sADPath); string sFilter = "(&(objectCategory=computer)(name=" + sComputerName + "))"; DirectorySearcher DirectorySearch = new DirectorySearcher(de, sFilter); SearchResult DirectorySearchResult = DirectorySearch.FindOne(); if (null != DirectorySearchResult) { DirectoryEntry deComp = DirectorySearchResult.GetDirectoryEntry(); oComputer.CN = deComp.Properties["cn"].Value.ToString(); .... }
编辑:
我误解了这个要求!它不是我需要的计算机的"物理"位置,而是AD层次结构中的位置.似乎应该在"abc.org - > A - > B"中的计算机不存在,但位于"abc.org - > A - > C - > D".我需要的是能够在给定计算机名称的情况下找到路径"abc.org - > A - > C - > D".
属性名称是"位置".与所有AD属性一样,如果搜索结果对象没有值,则不会在搜索结果对象上看到它.我已经摆弄了你的代码,以便它可以在我的机器上工作.
如果您只是检索数据而不打算进行任何更改,则无需调用GetDirectoryEntry(这将对服务器进行另一次往返).请注意语法上的细微差别:
var rootDSE = new DirectoryEntry("LDAP://RootDSE"); var defaultNamingContext = rootDSE.Properties["defaultNamingContext"].Value.ToString(); var domainRootADsPath = String.Format("LDAP://{0}", defaultNamingContext); var searchRoot = new DirectoryEntry(domainRootADsPath); var filter = "(&(objectCategory=computer)(name=" + computerName + "))"; var directorySearch = new DirectorySearcher(searchRoot, filter); var directorySearchResult = directorySearch.FindOne(); if (null != directorySearchResult) { Console.WriteLine(directorySearchResult.Properties["cn"][0].ToString()); if (directorySearchResult.Properties["location"].Count > 0) { Console.WriteLine(directorySearchResult.Properties["location"][0].ToString()); } //It's not necessary to run GetDirectoryEntry unless you want to make a change DirectoryEntry deComp = directorySearchResult.GetDirectoryEntry(); Console.WriteLine(deComp.Properties["cn"].Value.ToString()); if (deComp.Properties["location"].Value != null) { Console.WriteLine(deComp.Properties["location"].Value.ToString()); } }