Faster way to find out if a user exists on a system?

前端 未结 4 1183
陌清茗
陌清茗 2020-12-08 23:50

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         


        
4条回答
  •  离开以前
    2020-12-09 00:29

    .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;
    

提交回复
热议问题