Directory Synchronization in System.DirectoryServices ArgumentNull Exception

940 views Asked by At

I'm trying to access Active Directory Domain Services (ADDS) using System.DirectoryServices .NET Framework class library.

Using LDAP protocol, I want to get all DirectoryEntries that have an office set value attribute with this LDAP filter (physicalDeliveryOfficeName=*) and then I want to write the synchronization cookie to a file for future references just like an example shown in DirectorySynchronization msdn example article

Here's my code:

 using (DirectoryEntry de = new DirectoryEntry("LDAP://myDomain.com/OU=Test,DC=myDomain,DC=com"))
        {
            using (var ds = new DirectorySearcher(de))
            {
                ds.PropertiesToLoad.Add("distinguishedName");
                ds.SearchScope = SearchScope.Subtree;
                ds.Filter = "(physicalDeliveryOfficeName=*)";
                ds.DirectorySynchronization = new DirectorySynchronization();
                SearchResultCollection searchResultCollection = ds.FindAll();
                foreach (SearchResult result in searchResultCollection)
                {
                    var dn = (string)result.Properties["distinguishedName"][0];
                    //do Something
                }

                var cookie = ds.DirectorySynchronization.GetDirectorySynchronizationCookie();
                File.WriteAllBytes(@"location", cookie);
            }
        }

Each time I run this code

ds.DirectorySynchronization = new DirectorySynchronization();

I get a System.ArgumentNullException whenever I call ds.FindAll(). Knowing that whenever I comment the same line of code, I get a search result with no problems.

I hope I sound clear enough. For some reason I find this field has little documentation. I really cannot find an interpretation for this.

1

There are 1 answers

0
Nasri Yatim On BEST ANSWER

DirectorySynchronization must be assigned to a domain root LDAP path and does not work with sub-directories like an organizational unit.

using(DirectoryEntry de = new DirectoryEntry("LDAP://myDomain.com/DC=myDomain,DC=com")){

//same code

}

this will solve the issue.

In case anyone wants to track the changes in a sub-directory like OU's, they should use USNChanged.