【问题标题】:Get local user by SID通过 SID 获取本地用户
【发布时间】:2011-02-28 09:57:48
【问题描述】:

问题:我想按SID获取本地windows用户:

我找到了这段代码

[ADSI]("WinNT://$Env:Computername/<SID=S-1-5-18>")

这里: http://www.eggheadcafe.com/software/aspnet/32882679/add-builtin-account-to-local-group-using-winnt-adsi-provider.aspx

我从中推断,我可以在 (VB) .NET 中这样做:

Dim strURL As String = "WinNT://" + strComputerName + "/<SID=" + strSID + ">"
Dim de As DirectoryServices.DirectoryEntry = New DirectoryServices.DirectoryEntry(strURL)
de.Properties("whatever").Value.ToString()

但是,这不起作用。 任何人都知道我如何无需循环所有用户(这需要先从 byte[] 转换为字符串,然后比较 [不区分大小写] 很多字符串,这会使其变慢)。

【问题讨论】:

    标签: c# .net vb.net permissions directoryservices


    【解决方案1】:

    如果您使用的是 .NET 3.5 或更高版本,则可以使用此代码(在向您的项目添加对新 System.DirectoryServices.AccountManagement 命名空间的引用之后):

    using System.DirectoryServices.AccountManagement;
    
    // create a machine-context (local machine)
    PrincipalContext ctx = new PrincipalContext(ContextType.Machine);
    
    UserPrincipal up = UserPrincipal.FindByIdentity(ctx, IdentityType.Sid, <YourSidHere>);
    
    if (up != null)
    {
        Console.WriteLine("You've found: {0}", up.DisplayName);
    }
    else
    {
        Console.WriteLine("ERROR: no one found");
    }
    

    【讨论】:

    • 我在 .NET 2.0 上,此外,我已经有了获取 NTaccount 的代码。
    【解决方案2】:

    Win32 有 LookupAccountSid 函数,正是这样做的。

    请参阅PInvoke 了解如何从 VB.NET 使用。在您的情况下,域名将是本地计算机名称。

    【讨论】:

    • 不,DirectoryServices,不是 pinvoke。此外,如果我愿意,我可以在托管代码中获取 NTaccount。
    猜你喜欢
    • 2017-05-12
    • 2012-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多