문제

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!

다른 팁

You could use DirectorySearcher instead. Set a filter, call FindOne method and then check if result is null

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top