.NET(C#):有趣的IdentityReference和WindowsIdentity

來源:互聯網
上載者:User

這篇文章作為另一篇文章的補充:淺談.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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.