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?
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;
}
I know this is an old question, but the source code is now available so you can just Steal and Modify™ to make a version that accepts credentials:
public static bool Exists(string path, string username, string password)
{
DirectoryEntry entry = new DirectoryEntry(path, username, password);
try
{
_ = entry.NativeObject; // throws exceptions (possibly can break applications)
return true;
}
catch (System.Runtime.InteropServices.COMException e)
{
if (e.ErrorCode == unchecked((int)0x80072030) ||
e.ErrorCode == unchecked((int)0x80070003) || // ERROR_DS_NO_SUCH_OBJECT and path not found (not found in strict sense)
e.ErrorCode == unchecked((int)0x800708AC)) // Group name could not be found
return false;
throw;
}
finally
{
entry.Dispose();
}
}
The one change you must make is changing the use of Bind
, since that's an internal
method and can't be used by mere mortals like us. Instead, I just get the NativeObject
property, which calls Bind()
for us.
You can use that like this:
var ouExists = Exists("LDAP://hadoop.com/OU=Students,DC=hadoop,DC=com", "username", "password");
There is no way to do this and I have written a connect issue to hopefully resolve it.
DirectoryEntry.Exists Does Not Accept Credentials
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With