0

您能否帮助我并告诉我是否在我的目录服务函数中正确使用了“使用语句”,该函数从我的 Active Directory 中获取了专有名称。我想正确处理和关闭对象。

代码:

Public Function GetObjectDistinguishedName(ByVal objClass As objectClass, _  
    ByVal returnValue As returnType, _
    ByVal objName As String, ByVal LdapDomain As String, _  
    Optional ByVal includeLdapPrefix As Boolean = True) As String  

    Dim distinguishedName As String = String.Empty  
    Dim connectionPrefix = "LDAP://" & LdapDomain  

    Using entry As DirectoryEntry = New DirectoryEntry(connectionPrefix)
        Dim mySearcher = New DirectorySearcher(entry)
        Dim result As SearchResult
        Dim directoryObject As DirectoryEntry
        Select Case objClass
            Case objectClass.user
                mySearcher.Filter = "(&(objectClass=user)(|(cn=" + objName + ")(sAMAccountName=" + objName + ")))"
            Case objectClass.group
                mySearcher.Filter = "(&(objectClass=group)(|(cu=" + objName + ")(dn=" + objName + ")))"
            Case objectClass.computer
                mySearcher.Filter = "(&(objectClass=computer)(|(cn=" + objName + ")(dn=" + objName + ")))"
            Case objectClass.organizationalunit
                mySearcher.Filter = "(ou=" + objName + ")"
        End Select
        result = mySearcher.FindOne()

        If result Is Nothing Then 'If the search results in nothing, call for help!'
            Throw New NullReferenceException("Unable to locate the distinguishedName for the " & objClass.ToString & " : " & objName & " in the " & LdapDomain & " domain")
        End If

        directoryObject = result.GetDirectoryEntry()
        If returnValue.Equals(returnType.distinguishedName) Then
            If includeLdapPrefix Then
                distinguishedName = "LDAP://" & directoryObject.Properties("distinguishedName").Value
            Else
                distinguishedName = directoryObject.Properties("distinguishedName").Value
            End If
        End If
    End Using
    Return distinguishedName
End Function
4

1 回答 1

3

作为一般规则,您应该始终调用Dispose实现IDisposable. 两者兼而有之。DirectoryEntry_ 在您的代码示例中,只有第一个对象被处置。您还需要为and添加 using 块:DirectorySearcherIDisposableDirectoryEntrymySearcherdirectoryObject

Using entry As DirectoryEntry = New DirectoryEntry(connectionPrefix)
    Using mySearcher = New DirectorySearcher(entry)
        '...'
        Using directoryObject = result.GetDirectoryEntry()
            '...'
        End Using
    End Using
End Using

您实际上可以通过不使用并以以下方式直接从搜索结果中检索“distinguishedName”来减轻服务器上的负载GetDirectoryEntry(此代码未经测试,因为我目前不在域中):

mySearcher.PropertiesToLoad.Add("distinguishedName");
result = mySearcher.FindOne()
'...'
distinguishedName = result.Properties("distinguishedName")(0)
于 2010-10-04T20:41:32.333 回答