VB.Net access to the Active Directory


I have a VB.Net program that connects to AD using DirectoryServices. I can locate a user and retrieve properties for the account. My problem is that the search retrievs only certain properties using the PropertiesToLoad functionality, one of which is the users home directory, however if the home directory is blank for a given user then i get an 'Object reference not set to an instance of an object.' error when trying to put the property.value into a variable.

I have posted the portion of the code that is failing it fails on the _HomeDirPath = Results.GetDirectoryEntry().Properties("homedirectory").Value.ToString

It appears that the property is not loaded if blank is there a way i can check for the property not being loaded.

            _DSearch.Filter = "(&(objectClass=user) (SAMAccountName=" + UserID + "))"
            Dim Results As SearchResult = _DSearch.FindOne()
            _CommonName = Results.GetDirectoryEntry().Properties("CN").Value
            _DistinguishedName = Results.GetDirectoryEntry().Properties("distinguishedName").Value
            _HomeDirPath = Results.GetDirectoryEntry().Properties("homedirectory").Value.ToString
            If Not _HomeDirPath.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()) Then
                _HomeDirPath &= System.IO.Path.DirectorySeparatorChar
            End If
            _SurName = Results.GetDirectoryEntry().Properties("SN").Value
            _UserProfile = UserID
        Catch ex As Exception

Open in new window

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Put that in a separate try/catch block, and in the catch section set the variable to "?".  Then after you exit that try/catch, just check the value.  If it's "?" then you know the AD value was blank.


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
JJKingAuthor Commented:
Thanks for that, dont know why i didnt think of that myself.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Active Directory

From novice to tech pro — start learning today.