找出用户是否存在于系统上的更快方法?

Faster way to find out if a user exists on a system?(找出用户是否存在于系统上的更快方法?)

本文介绍了找出用户是否存在于系统上的更快方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,每次启动时都会检查用户是否存在(如果没有创建).这是按如下方式完成的:

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;
DirectoryEntry dirEntryLocalMachine = 
    new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");

DirectoryEntries dirEntries = dirEntryLocalMachine.Children;

foreach (DirectoryEntry dirEntryUser in dirEntries)
{
    bUserExists = dirEntryUser.Name.Equals("UserName", 
        StringComparison.CurrentCultureIgnoreCase);

    if (bUserExists)
      break;
}

问题出在部署它的大多数系统上.这可能需要 6 - 10 秒,太长了......我需要找到一种方法来减少这种情况(尽可能多).有没有更好更快的方法来验证系统上是否存在用户?

The problem is on the majority of the systems where it is deployed. This can take 6 - 10 seconds, which is too long ... I need to find a way to reduce this (as much as possible). Is there a better or faster way I can use to verify if a user exists on the system or not?

我知道还有其他方法可以解决这个问题,比如让其他应用程序休眠 10 秒,或者让这个工具在准备好时发送消息等等......但是如果我能大大减少它花费的时间找到用户,这会让我的生活更轻松.

I know there are other ways to solve this, like have the other applications sleep for 10 seconds, or have this tool send a message when it is ready, etc... But if I can greatly reduce the time it takes to find the user, it would make my life much easier.

推荐答案

.NET 3.5支持 AD 查询类/en-us/library/system.directoryservices.accountmanagement(v=vs.90).aspx" rel="noreferrer">System.DirectoryServices.AccountManagement 命名空间.

.NET 3.5 supports new AD querying classes under the System.DirectoryServices.AccountManagement namespace.

要使用它,您需要添加System.DirectoryServices.AccountManagement"作为参考,并添加using 语句.

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

对于 3.5 之前的 .NET 版本,这是我在 dotnet-snippets

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;

这篇关于找出用户是否存在于系统上的更快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:找出用户是否存在于系统上的更快方法?

基础教程推荐