Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DirectoryEntries.Find: "An invalid dn syntax has been specified"

I'm trying to find a user in the current domain. The code is this:

DirectoryEntry domain = new DirectoryEntry("LDAP://CN-Users, DC=" + Environment.UserDomainName);
            DirectoryEntries entries = domain.Children;
            try
            {
                // The following line causes the exception
                DirectoryEntry user = entries.Find("(&(objectCategory=user)(cn=" + userName + "))", ActiveDirectoryEntryType.User.TypeName);
                user.DeleteTree();
                user.CommitChanges();
            }
            catch
            {}

I'm getting an error:

An invalid dn syntax has been specified.

I also tried the following code and got the same error:

DirectoryEntry user = entries.Find(userName, ActiveDirectoryEntryType.User.TypeName);

I could not find information about the proper syntax in the help files. Does anyone know how this is done?

like image 763
user884248 Avatar asked Oct 04 '22 07:10

user884248


1 Answers

You have an error in this statemet:

DirectoryEntry domain = new DirectoryEntry("LDAP://CN-Users, DC=" + Environment.UserDomainName);

I almost sure that it should be: LDAP://CN=Users, instaed of LDAP://CN-Users,

Second thing is DC=" + Environment.UserDomainName which maybe wrong, because ususally it is something like this: LDAP://OU=Finance,dc=fabrikam,dc=com (there is more than one DC)

You can find all DC using powershell. Run following command:

New-Object DirectoryServices.DirectoryEntry
like image 97
Piotr Stapp Avatar answered Oct 13 '22 11:10

Piotr Stapp