2012-07-20 19 views
17

Me gustaría convertir el tipo SID System.Byte [] a String.Cómo convertir SID a String en .net

Mi código:

string path = "LDAP://DC=abc,DC=contoso,DC=com"; 
DirectoryEntry entry = new DirectoryEntry(path); 
DirectorySearcher mySearcher = new DirectorySearcher(entry); 

mySearcher.Filter = "(&(objectClass=user)(samaccountname=user1))"; 
results = mySearcher.FindAll(); 
foreach (SearchResult searchResult in results) 
{ 
    Console.WriteLine(searchResult.Properties["ObjectSID"][0].ToString()); 
} 

me trató con esto, pero obtiene los valores del dominio Actualmente estoy inscrito, y que necesito de un dominio dado.

System.Security.Principal.NTAccount(user1) 
    .Translate([System.Security.Principal.SecurityIdentifier]).value 

Respuesta

34

Eche un vistazo a la clase SecurityIdentifier. A continuación, puede hacer cosas simples como,

var sidInBytes = (byte[]) *somestuff* 
var sid = new SecurityIdentifier(sidInBytes, 0); 
// This gives you what you want 
sid.ToString(); 
1

Esto es lo que he hecho yo, después de algún leerlo parecía más seguro para almacenar el valor en octubre. Si no sabe qué servidores está del otro lado. El código siguiente muestra cómo hacerlo para conseguir el resultado deseado

private static string ExtractSinglePropertyValueFromByteArray(object value) 
{ 
    //all if checks etc has been omitted 
    string propertyValue = string.Empty; 
    var bytes = (byte[])value; 
    var propertyValueOct = BuildOctString(bytes); // 010500....etc 
    var propertyValueSec = BuildSecString(bytes); // S-1-5-...etc 
    propertyValue = propertyValueSec; 
    return propertyValue; 
} 

private static string BuildSecString(byte[] bytes) 
{ 
    return new SecurityIdentifier(bytes,0).Value.ToString(); 
} 

private static string BuildOctString(byte[] bytes) 
{ 
    StringBuilder sb = new StringBuilder(); 
    for (int i = 0; i < bytes.Length; i++) 
    { 
     sb.Append(bytes[i].ToString("X2")); 
    } 
    return sb.ToString(); 
} 
0

Después de la carga con el establecimiento con DirectoryEntry ....

var usrId = (byte[])directoryEntry.Properties["objectSid"][0]; 
var objectID = (new SecurityIdentifier(usrId,0)).ToString();