有沒有人知道在C#和VB.NET中的DirectorySearcher對象上的FindAll()方法的實現之間是否有區別?根據我的理解,它們都被「編譯」爲MSIL,並以相同的方式被CLR處理。針對我們的ADAM/LDAP系統,下面的C#代碼會拋出一個錯誤,而下面的VB.NET不會。C#和VB.NET LDAP搜索不同?
這裏是C#異常堆棧:
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_AdsObject()
at System.DirectoryServices.DirectorySearcher.FindAll(Boolean findMoreThanOne)
at System.DirectoryServices.DirectorySearcher.FindAll()
這裏是C#錯誤:
System.Runtime.InteropServices.COMException was unhandled
Message="The parameter is incorrect.\r\n"
Source="System.DirectoryServices"
ErrorCode=-2147024809
C#代碼:
private void button1_Click(object sender, EventArgs e)
{
DirectoryEntry root = new DirectoryEntry("LDAP://directory.corp.com/OU=Person,OU=Lookups,O=Corp,C=US", null, null, AuthenticationTypes.Anonymous);
DirectorySearcher mySearcher = new DirectorySearcher(root);
mySearcher.Filter = "(uid=ssnlxxx)";
mySearcher.PropertiesToLoad.Add("cn");
mySearcher.PropertiesToLoad.Add("mail");
SearchResultCollection searchResultCollection = null;
searchResultCollection = mySearcher.FindAll(); //this is where the error occurs
try
{
foreach (SearchResult resEnt in searchResultCollection)
{
Console.Write(resEnt.Properties["cn"][0].ToString());
Console.Write(resEnt.Properties["mail"][0].ToString());
}
}
catch (DirectoryServicesCOMException ex)
{
MessageBox.Show("Failed to connect LDAP domain, Check username or password to get user details.");
}
}
這是VB.NET代碼工作:
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim root As New DirectoryEntry("LDAP://directory.corp.com/OU=People,OU=Lookups,O=corp,C=US", vbNull, vbNull, authenticationType:=DirectoryServices.AuthenticationTypes.Anonymous)
Dim searcher As New DirectorySearcher(root)
searcher.Filter = "(uid=ssnlxxx)"
searcher.PropertiesToLoad.Add("cn")
searcher.PropertiesToLoad.Add("mail")
Dim results As SearchResultCollection
Try
results = searcher.FindAll()
Dim result As SearchResult
For Each result In results
Console.WriteLine(result.Properties("cn")(0))
Console.WriteLine(result.Properties("mail")(0))
Next result
Catch ex As Exception
MessageBox.Show("There was an error")
End Try
End Sub
什麼是異常消息? – Yuck 2011-05-20 14:59:29
我不知道這會解決你的問題_(所以我評論,而不是'回答...'),但在你的c#代碼中你可能會改變'「LDAP://directory.corp.com/OU= Person,OU = Lookups,O = Corp,C = US「'到'@」LDAP://directory.corp.com/OU=Person,OU=Lookups,O=Corp,C=US「'。 @符號告訴C#編譯器忽略轉義字符,這是C#和VB.NET之間可能直接影響這個問題的少數差異之一。 – 2011-05-20 14:59:46
什麼是VB.NET代碼中的'vbNull'?這與「Nothing」不同嗎? – 2011-05-20 15:07:33