bass
bass

Reputation: 3

DirectorySearcher Class Out of Range Exception

I can't seem to return any meaningful search results when I perform a directory search for a BitLocker recovery key.

DirectoryEntry entry = new DirectoryEntry("LDAP://OU=MYOU,DC=MYDC", adminUsername,
            adminPassword);
        entry.Username = AdminInformation.AdminUsername;
        entry.Password = AdminInformation.AdminPassword;

        DirectorySearcher search = new DirectorySearcher(entry);
        search.PropertiesToLoad.Add("msFVE-RecoveryPassword");
        search.Filter = $"(&(cn={chosenComputer}))";

        foreach (SearchResult res in result)
        {
            textBoxBitLockerKey.Text = (res.Properties["msFVE-RecoveryPassword"][0].ToString());
        }

Basically I populated a list with computers that would contain the BitLocker key (we only have laptops that use BitLocker in our organization). After the user selects the laptop then the associated BitLocker key should be populated in a text box that they can copy or print, but everytime I try to grab that key from the selected computer, I keep getting an out of bounds exception. I've been using DirectorySearcher to find other properties such as a user account or computer name, but this is giving me trouble. I understand what the error is I just don't know what is causing it and I can't seem to find any other answers that quite cover this topic. Any input is appreciated.

Here's the exception: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index.

Upon further investigation, it appears that the directorysearcher is only searching for properties that encapsulate the msFVE-RecoveryInformation property. If i try to add a filter based on a chosen computer name, it will not provide a SearchResult property with an actual value. If I try to set the filter based on "cn", for example, it returns the GUID for the BitLocker key.

Upvotes: 0

Views: 519

Answers (1)

Cee McSharpface
Cee McSharpface

Reputation: 8725

Whenever I query a non-mandatory property from AD by LDAP (a property, that is not necessarily present on all objects the DirectorySearcher finds), I use this pattern:

const string propertykey = "msFVE-RecoveryPassword";
if (res.Properties.Contains(propertykey))
{
    string value = res.Properties[propertykey][0].ToString();
}

Using the [0] index is generally considered safe on single-values properties; you may want to add a check for Count > 0 if you are dealing with a multi-value property (or use an enumerator).

Upvotes: 1

Related Questions