I have an application that checks to see if a user exists (if not create it) every time it starts. This is done as follows:
bool bUserExists = false;
Directo
.NET 3.5 supports new AD querying classes under the System.DirectoryServices.AccountManagement namespace.
To make use of it, you'll need to add "System.DirectoryServices.AccountManagement" as a reference AND add the using
statement.
using System.DirectoryServices.AccountManagement;
using (PrincipalContext pc = new PrincipalContext(ContextType.Machine))
{
UserPrincipal up = UserPrincipal.FindByIdentity(
pc,
IdentityType.SamAccountName,
"UserName");
bool UserExists = (up != null);
}
< .NET 3.5
For versions of .NET prior to 3.5, here is a clean example I found on dotnet-snippets
DirectoryEntry dirEntryLocalMachine =
new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
bool UserExists =
dirEntryLocalMachine.Children.Find(userIdentity, "user") != null;
You want to use the DirectorySearcher.
Something like this:
static bool userexists( string strUserName ) {
string adsPath = string.Format( @"WinNT://{0}", System.Environment.MachineName );
using( DirectoryEntry de = new DirectoryEntry( adsPath ) ) {
try {
return de.Children.Find( strUserName ) != null;
} catch( Exception e ) {
return false;
}
}
}
That should be quicker. Also, you can reduce the properties if all you are doing is checking for existence.
The following in a command prompt returns 1 if 'username' exists.
net user | find "username" /c
This should do it (when you can't use System.DirectoryServices.AccountManagement):
static bool userExists(string sUser)
{
using (var oUser = new DirectoryEntry("WinNT://" + Environment.MachineName + "/" + sUser + ",user"))
{
return (oUser != null);
}
}