這篇文章作為另一篇文章的補充:淺談.NET(C#)與Windows使用者賬戶資訊的擷取
當你得到一個WindowsIdentity對象,怎樣擷取它的兩種IdentityReference:SecurityIdentifier和NTAccount?首先這兩個子類擷取一個類就可以,另一個直接從IdentityReference.Translate方法中得到便可以。不同類型的IdentityReference其Value屬性往往不一樣。
首先對於WindowsIdentity對象,它的User屬性返回對應使用者的SID,就是一個SecurityIdentifier對象,這樣也可以順便得出NTAccount:
//+ using System.Security.Principal;
WindowsIdentity wi = WindowsIdentity.GetCurrent();
//全稱
Console.WriteLine(wi.User.Translate(typeof(NTAccount)).Value);
//SID
Console.WriteLine(wi.User.Value);
另一種方法就是從WindowsIdentity的Name屬性,這個Name屬性不是WindowsIdentity特有的,是繼承與IIdentity介面,在WindowsIdentity下代表著目前使用者的全程。這個全程便可以建立一個NTAccount對象,然後用Translate方法得到SecurityIdentifier。
如下代碼:
//+ using System.Security
//+ using System.Security.Principal;
IIdentity ii = WindowsIdentity.GetCurrent();
//建立NTAccount
NTAccount ntacc = new NTAccount(ii.Name);
//全稱
Console.WriteLine(ntacc.Value);
//SID
Console.WriteLine(ntacc.Translate(typeof(SecurityIdentifier)).Value);
他們都會輸出目前使用者賬戶的全程和SID,比如我的電腦是這樣的:
Mgen-PC\Mgen
S-1-5-21-2376214308-3361272619-2153758801-1000