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;
这篇关于找出用户是否存在于系统上的更快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:找出用户是否存在于系统上的更快方法?
基础教程推荐
- 从 VB6 迁移到 .NET/.NET Core 的最佳策略或工具 2022-01-01
- 覆盖 Json.Net 中的默认原始类型处理 2022-01-01
- 创建属性设置器委托 2022-01-01
- 如何使用OpenXML SDK将Excel转换为CSV? 2022-01-01
- Page.OnAppearing 中的 Xamarin.Forms Page.DisplayAlert 2022-01-01
- 当键值未知时反序列化 JSON 2022-01-01
- C# - 如何列出发布到 ASPX 页面的变量名称和值 2022-01-01
- 使用 SED 在 XML 标签之间提取值 2022-01-01
- C# - 将浮点数转换为整数...并根据余数更改整数 2022-01-01
- 我什么时候应该使用 GC.SuppressFinalize()? 2022-01-01