[英]C# and VB.NET LDAP Search Different?
有誰知道C#和VB.NET中DirectorySearcher對象上的FindAll()方法的實現是否有區別? 根據我的理解,它們都被“編譯”到MSIL並由CLR以相同的方式處理。 與我們的ADAM / LDAP系統相反,下面的C#代碼會拋出錯誤,而下面的VB.NET則不會。
這是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
我猜想在VB.NET代碼中,你在DirectoryEntry
構造函數中為兩個參數傳遞vbNull
(而不是Nothing
),並且在C#代碼中傳遞null
。 vbNull
大概來自邪惡的Microsoft.VisualBasic
程序集,不應該使用它。
DirectoryEntry
的構造函數檢查用戶名和密碼參數以查看它們是否為空。 如果vbNull != Nothing
,構造函數將不會將它們視為null並且行為會有所不同。
如果你使用Nothing
,看看VB.NET代碼是否拋出異常,或者看看C#代碼是否通過使用String.Empty
而不是null
。
此外,在您的C#代碼中,對FindAll
的調用不在try塊之內。
C#和VB.NET都沒有實現DirectorySearcher
或.NET的任何其他部分。 它們都是.NET Framework的一部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.