我有一个应用程序,它可以在每次启动时检查用户是否存在(如果不是创建的话)。这项工作如下:
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秒,太长了.我需要找到一种方法来减少这种情况(尽可能多)。是否有更好或更快的方法来验证用户是否存在于系统中?
我知道有其他方法可以解决这个问题,比如让其他应用程序睡上10秒,或者让这个工具在准备好的时候发送消息等等。但是,如果我能大大减少找到用户所需的时间,我的生活就会轻松得多。
发布于 2009-11-04 18:53:19
.NET 3.5支持System.DirectoryServices.AccountManagement
命名空间下的新广告查询类。
要使用它,您需要添加"System.DirectoryServices.AccountManagement“作为引用,并添加using
语句。
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-片段上找到的一个简单示例
DirectoryEntry dirEntryLocalMachine =
new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
bool UserExists =
dirEntryLocalMachine.Children.Find(userIdentity, "user") != null;
发布于 2009-11-04 19:00:58
您想要使用DirectorySearcher。
就像这样:
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;
}
}
}
那应该更快些。此外,如果您所做的只是检查是否存在,则可以减少属性。
发布于 2021-09-29 16:57:27
另一种方法是(支持本地或域用户):
bool UserExists(string userName)
{
var user = new NTAccount(userName);
try
{
var sid = (SecurityIdentifier)user.Translate(typeof(SecurityIdentifier));
return true;
}
catch (IdentityNotMappedException)
{
return false;
}
}
用户可以是不合格的,也可以是由计算机/域名(DOMAIN\UserName
)限定的。如果需要专门检测帐户是否存在于本地计算机上,请使用Environment.MachineName
($"{Environment.MachineName}\\{userName}"
)对其进行限定。
https://stackoverflow.com/questions/1675813
复制相似问题