简体   繁体   中英

From SID get user@domain not domain\user

This is a bit of an obscure one: I need to get the user@domain form of a user/group, but I do NOT want the domain\\user form. I encountered a problem once with long windows 2003+ names where the two are NOT the same because of the domain\\user length limit, because the new form does not have the limit.

I'm under C#, and while I can do the following:

string GetUserName(SecurityIdentifier SID)
{
    NTAccount account = SID.Translate(typeof(NTAccount));
    string [] splits = string.Split("\\", account.Value);
    return splits[1] + @"@" + splits[0];
}

This isn't always right, as I stated in my intro, the username@domain is NOT NECESSARILY the same as the old windows NT form of the username. If you don't believe me, go into AD Users and computers on a 2k3+ box and see how there's different fields for the old NT username versus the new one.

So how do I guarantee I get the right username@domain from a SID? Add to that, I also need this type of thing to work for local users/groups.

The Windows API to get this is called DsCrackNames - http://msdn.microsoft.com/en-us/library/ms675970 . It will give you the output in any number of formats depending on the flags you provide.

Can't you use System.DirectoryServices.AccountManagement.Principal and the UPN (your name@domain.com) to look up the Sid (also a property on the principal)?
http://msdn.microsoft.com/en-us/library/bb340707.aspx

Here is a TechNet snippet that uses a DirectorySearcher to search for a user by UPN
http://gallery.technet.microsoft.com/ScriptCenter/de2cb677-f930-40a5-867d-ea0326ccbcdb/

After fetching the principal you should be able to get the Sid property.

I have post some C# code for retreiving user data from SID , here is the same aapted to your question :

/* Retreiving object from SID 
  */ 
string SidLDAPURLForm = "LDAP://WM2008R2ENT:389/<SID={0}>"; 
System.Security.Principal.SecurityIdentifier sidToFind = new System.Security.Principal.SecurityIdentifier("S-1-5-21-3115856885-816991240-3296679909-1106"); 

DirectoryEntry userEntry = new DirectoryEntry(string.Format(SidLDAPURLForm, sidToFind.Value)); 
string name = userEntry.Properties["userPrincipalName"].Value.ToString(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM