Log in using AD credentials in C#


I am using following code to validate AD users

string strLDAP = "LDAP://dc=ADServerIP/cn=Users,DC=Domain;
DirectoryEntry entry = new DirectoryEntry(strLDAP, usr, pwd);
object nativeObject = entry.NativeObject;
return true;

I am getting the following exception when executing

object nativeObject = entry.NativeObject;

System.Runtime.InteropServices.COMException (0x80005000): Unknown error (0x80005000)
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_NativeObject()

The same code is working for another AD server. What may be the issue?

asked on Stack Overflow Jun 4, 2012 by vml19 • edited Jun 4, 2012 by marc_s

1 Answer


Are you working on .NET 3.5 or newer? If so, you can use the System.DirectoryServices.AccountManagement namespace and easily verify your credentials:

// create a "principal context" - e.g. your domain (could be machine, too)
using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN", usr, pwd))
    // validate the credentials
    bool isValid = pc.ValidateCredentials("myuser", "mypassword");

It's simple, it's reliable, it's 100% C# managed code on your end - what more can you ask for? :-)

Read all about it here:

answered on Stack Overflow Jun 4, 2012 by marc_s

User contributions licensed under CC BY-SA 3.0