If I understand your question correctly, I would do it like this:
Public Function GetDirectoryEntry(ByVal Path As String) As DirectoryEntry
Dim Result As DirectoryEntry = Nothing
Try
Result = New DirectoryEntry(Path)
Dim Test As System.Guid = Result.Guid
Catch ex As Exception
Result.Close
Result = Nothing
End Try
Return Result
End Function
Public Sub Main
Dim DirEntry As DirectoryEntry = GetDirectoryEntry(Path)
If DirEntry Is Nothing Then
'The path is invalid
Else
'The path is valid
'Use it
DirEntry.Close
End If
End Sub
If
Path is valid, then the function will return an open, valid
DirectoryEntry
object. Otherwise, it will return
Nothing
.
Using
Try
/
Catch
blocks to determine valid values is bad form, but Active Directory doesn't seem to give us any other choice. Regardless of
Path, you will get your
DirectoryEntry
even if the path was not found. The only way to know if the object is valid is to look at one of its values and fail. At least, that is my experience.
Update: :doh: The function is returning an open
DirectoryEntry
; it will need to be closed, otherwise you have a memory leak. I added the
Dim
statement to
Main
to hold the object returned by the function; do with it as you will.