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

前端 未结 4 1184
陌清茗
陌清茗 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;
    
    0 讨论(0)
  • 2020-12-09 00:33

    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.

    0 讨论(0)
  • 2020-12-09 00:35

    The following in a command prompt returns 1 if 'username' exists.

    net user | find "username" /c

    0 讨论(0)
  • 2020-12-09 00:43

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题