找出用户是否存在于系统上的更快方法?
- 作者: 啃得鸡
- 来源: 51数据库
- 2022-10-21
问题描述
我有一个应用程序,每次启动时都会检查用户是否存在(如果没有创建).这是按如下方式完成的:
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;
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
