How to provide DirectoryEntry.Exists with credentials?

Herman Cordes picture Herman Cordes · Nov 26, 2010 · Viewed 13.8k times · Source

This morning I discovered a nice method (DirectoryEntry.Exists), that should be able to check whether an Active Directory object exists on the server. So I tried with a simple:

if (DirectoryEntry.Exists(path)) {}

Of course it lacks any overloads to provide credentials with it. Because, if credentials are not provided I get this Exception:

Logon failure: unknown user name or bad password. (System.DirectoryServices.DirectoryServicesCOMException)

Is there any other option that gives me the possibility to authenticate my code at the AD server? Or to check the existence of an object?

Answer

JoeBilly picture JoeBilly · Nov 26, 2010

In this case you can't use the static method Exists as you said :

DirectoryEntry directoryEntry = new DirectoryEntry(path);
directoryEntry.Username = "username";
directoryEntry.Password = "password";

bool exists = false;
// Validate with Guid
try
{
    var tmp = directoryEntry.Guid;
    exists = true;
}
catch (COMException)
{
   exists = false; 
}