Get local user by SID
Question: I want to get a local windows user by SID:
I found this code
[ADSI]("WinNT://$Env:Computername/<SID=S-开发者_StackOverflow中文版1-5-18>")
here: http://www.eggheadcafe.com/software/aspnet/32882679/add-builtin-account-to-local-group-using-winnt-adsi-provider.aspx
I deduced from it, I could do it in (VB) .NET with this:
Dim strURL As String = "WinNT://" + strComputerName + "/<SID=" + strSID + ">"
Dim de As DirectoryServices.DirectoryEntry = New DirectoryServices.DirectoryEntry(strURL)
de.Properties("whatever").Value.ToString()
However, this doesn't work. Anybody knows how I can do this WITHOUT looping over all users (which requires to convert from byte[] to string first, and then compare [case insensitive] a lot of strings, which makes it slow).
If you're on .NET 3.5 or newer, you can use this code (after adding a reference to the new System.DirectoryServices.AccountManagement
namespace to your project):
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");
}
Win32 has the LookupAccountSid function, which does exactly this.
See PInvoke for how to use from VB.NET. In your case, the domain name will be the local computer name.
精彩评论