2012-07-20 27 views
17

Tôi muốn chuyển đổi kiểu System.Byte [] của SID thành một Chuỗi.Cách chuyển đổi SID thành Chuỗi trong .net

Mã của tôi:

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()); 
} 

tôi đã cố gắng với điều này nhưng nó được các giá trị từ các miền Tôi hiện đang đăng nhập, và tôi cần từ một tên miền nhất định.

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

Trả lời

34

Hãy xem qua lớp SecurityIdentifier. Sau đó bạn có thể làm những việc đơn giản như,

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

Đây là những gì tôi đã làm, sau khi đọc một số dường như an toàn hơn để lưu trữ giá trị trong oct. Nếu bạn không biết máy chủ nào ở phía bên kia. Đoạn code dưới đây cho thấy làm thế nào để làm điều đó để có được kết quả mong muốn của bạn

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

Sau khi tải tài sản trong DirectoryEntry ....

var usrId = (byte[])directoryEntry.Properties["objectSid"][0]; 
var objectID = (new SecurityIdentifier(usrId,0)).ToString(); 
Các vấn đề liên quan