I have the following code that removes a local user account from the AD:
try
{
string username = "MyUserName";
using (DirectoryEntry hostMachineDirectory = new DirectoryEntry("WinNT://localhost"))
{
DirectoryEntries entries = hostMachineDirectory.Children;
DirectoryEntry deUser = null;
try
{
deUser = entries.Find(username, "User");
}
catch (COMException ex)
{
//Look for "no such user" exception
if ((uint)ex.ErrorCode != 0x800708ad)
{
throw ex;
}
}
if (deUser != null)
entries.Remove(deUser);
else
ShowMessageBoxError("No such user: " + username, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
ShowMessageBoxError(ex);
}
Is there any way to avoid raising and catching that exception in case there's no such user?
If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement
(S.DS.AM) namespace. Read all about it here:
Basically, you can define a domain context and easily find users and/or groups in AD:
// set up context to your local machine only
using (PrincipalContext ctx = new PrincipalContext(ContextType.Machine))
{
// find your user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, username);
if(user != null)
{
// if user is found - remove it
user.Delete();
}
}
The new S.DS.AM makes it really easy to play around with users and groups in AD!