取得登入帳號
Environment.UserName
取得帳號等有儲存在本機上的資訊
using System.Security.Principal;
using System.Threading;
//-----
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
WindowsPrincipal myPrincipal = (WindowsPrincipal)Thread.CurrentPrincipal;
WindowsIdentity myIdentity = (WindowsIdentity)myPrincipal.Identity;
Console.WriteLine("IdentityType: " + myIdentity.ToString());
Console.WriteLine("Name: {0}", myIdentity.Name);
Console.WriteLine("Member of Users? {0}", myPrincipal.IsInRole(WindowsBuiltInRole.User));
Console.WriteLine("Member of Administrators? {0}", myPrincipal.IsInRole(WindowsBuiltInRole.Administrator));
Console.WriteLine("Authenticated: {0}", myIdentity.IsAuthenticated);
Console.WriteLine("Anonymous: {0}", myIdentity.IsAnonymous);
取得帳號等有儲存在本機上的資訊 - II
使用 Win32 API
using System.Runtime.InteropServices;
//-----
[DllImport("Advapi32.dll", EntryPoint="GetUserName", ExactSpelling=false, SetLastError=true)]
static extern bool GetUserName([MarshalAs(UnmanagedType.LPArray)] byte[] lpBuffer,
[MarshalAs(UnmanagedType.LPArray)] Int32[] nSize );
//-----
byte[] str = new byte[256];
Int32[] len = new Int32[1];
len[0] = 256;
GetUserName(str, len);
MessageBox.Show(System.Text.Encoding.ASCII.GetString(str));
string a = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
MessageBox.Show(a.ToString());
LDAP
這是可以取得最詳細資訊的方法
using System.DirectoryServices;
//-----
string principal = Environment.UserName;
string filter = string.Format("(&(ObjectClass={0})(sAMAccountName={1}))", "person", principal);
string[] properties = new string[] { "fullname" };
//用匿名登入,理論上LDAP都會允許,但只有 read 權限
DirectoryEntry adRoot = new DirectoryEntry("LDAP://yourdomain.com", null, null, AuthenticationTypes.Secure);
DirectorySearcher searcher = new DirectorySearcher(adRoot);
searcher.SearchScope = SearchScope.Subtree;
searcher.ReferralChasing = ReferralChasingOption.All;
searcher.PropertiesToLoad.AddRange(properties);
searcher.Filter = filter;
SearchResult result = searcher.FindOne();
DirectoryEntry directoryEntry = result.GetDirectoryEntry();
string displayName = directoryEntry.Properties["displayName"][0].ToString();
string firstName = directoryEntry.Properties["givenName"][0].ToString();
string lastName = directoryEntry.Properties["sn"][0].ToString();
string email = directoryEntry.Properties["mail"][0].ToString();
string department = directoryEntry.Properties["department"][0].ToString();
string description = directoryEntry.Properties["description"][0].ToString();