更快的方法来找出用户是否存在的系统上? [英] 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 的System.DirectoryServices.AccountManagement命名空间下查询类。
.NET 3.5 supports new AD querying classes under the System.DirectoryServices.AccountManagement namespace.
要使用它,你需要添加System.DirectoryServices.AccountManagement作为参考,并添加使用
语句。
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
有关.NET之前的3.5版本,这里是一个干净的例子,我发现的 DOTNET-片段
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;
这篇关于更快的方法来找出用户是否存在的系统上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!