基于.Net Framework 4.0, 使用Windows Identity类可获取当前账户的相关信息,包含账户名称,SID,组成员关系等。代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Principal; namespace WindowsSecurityViaCSharp { class Program { static void Main(string[] args) { WindowsIdentity winIdentity = WindowsIdentity.GetCurrent(); if (winIdentity == null) { Console.WriteLine("Cannot get current user identity. Exiting..."); return; } Console.WriteLine("Current machine name:\t" + Environment.MachineName); Console.WriteLine("Current user name:\t" + winIdentity.Name); Console.WriteLine("Current user authentication type:\t" + winIdentity.AuthenticationType); Console.WriteLine("Current user SID:\t" + winIdentity.User); Console.WriteLine("Current user token:\t" + winIdentity.Token); Console.WriteLine("Token owner SID:\t" + winIdentity.Owner); Console.WriteLine("Current user has {0} group memberships.", winIdentity.Groups.Count); foreach (IdentityReference group in winIdentity.Groups) { NTAccount ntAcc = (NTAccount)group.Translate(typeof(NTAccount)); Console.WriteLine("\tGroup {0}", ntAcc.Value); } } } }