Sha*_*n00 8 c# windows active-directory
我有一个应用程序,每次启动时都会检查用户是否存在(如果没有创建).这样做如下:
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;
}
Run Code Online (Sandbox Code Playgroud)
问题在于部署它的大多数系统.这可能需要6-10秒,这太长了......我需要找到一种方法来减少这种情况(尽可能多).有没有更好或更快的方法来验证系统上是否存在用户?
我知道还有其他方法可以解决这个问题,例如让其他应用程序休眠10秒,或者让这个工具在准备就绪时发送消息等等......但是如果我可以大大减少查找用户所需的时间,它会让我的生活更轻松.
Mic*_*oie 22
.NET 3.5支持命名空间下的新AD查询类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);
}
Run Code Online (Sandbox Code Playgroud)
<.NET 3.5
对于3.5之前的.NET版本,这是我在dotnet-snippets上找到的一个干净的例子
DirectoryEntry dirEntryLocalMachine =
new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
bool UserExists =
dirEntryLocalMachine.Children.Find(userIdentity, "user") != null;
Run Code Online (Sandbox Code Playgroud)
您想使用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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
那应该更快.此外,如果您正在检查是否存在,则可以减少属性.