今天學習下怎麼用.Net獲取系統當前登錄用戶名,由於目前網上基本只有最簡單的方式,但以管理員身份運行的話就會獲取不到,因此特整理一下做爲分享,最後附帶參考文檔,方便深究的童鞋繼續學習。html
========== 原創做品,未經本人容許,請勿轉載,謝謝! ==========api
========== 做者:Yokeqi 出處:博客園 原文連接 ==========session
1、知識點簡單介紹dom
相信不少人第一直覺是使用.net的環境變量。ide
Environment.UserName
可是可能不少人找我這篇文章是由於這個環境變量其實會受到管理員身份運行的影響,獲取到的是管理員的身份,而不是真實的當前登陸用戶。函數
這裏的思路是利用WindowsApi進行獲取,通過各類查資料獲得一個Api函數學習
[DllImport("Wtsapi32.dll")] protected static extern bool WTSQuerySessionInformation(IntPtr hServer, int sessionId, WTSInfoClass wtsInfoClass, out IntPtr ppBuffer, out uint pBytesReturned);
2、具體實例演示如何實現ui
1. 引入API接口this
[DllImport("Wtsapi32.dll")] protected static extern void WTSFreeMemory(IntPtr pointer); [DllImport("Wtsapi32.dll")] protected static extern bool WTSQuerySessionInformation(IntPtr hServer, int sessionId, WTSInfoClass wtsInfoClass, out IntPtr ppBuffer, out uint pBytesReturned);
這裏引入 WTSFreeMemory 方法主要用於對非託管資源的釋放。spa
2. WTSInfoClass類定義
public enum WTSInfoClass { WTSInitialProgram, WTSApplicationName, WTSWorkingDirectory, WTSOEMId, WTSSessionId, WTSUserName, WTSWinStationName, WTSDomainName, WTSConnectState, WTSClientBuildNumber, WTSClientName, WTSClientDirectory, WTSClientProductId, WTSClientHardwareId, WTSClientAddress, WTSClientDisplay, WTSClientProtocolType, WTSIdleTime, WTSLogonTime, WTSIncomingBytes, WTSOutgoingBytes, WTSIncomingFrames, WTSOutgoingFrames, WTSClientInfo, WTSSessionInfo }
3. 獲取當前登陸用戶方法的具體實現
/// <summary> /// 獲取當前登陸用戶(可用於管理員身份運行) /// </summary> /// <returns></returns> public static string GetCurrentUser() { IntPtr buffer; uint strLen; int cur_session = -1; var username = "SYSTEM"; // assume SYSTEM as this will return "\0" below if (WTSQuerySessionInformation(IntPtr.Zero, cur_session, WTSInfoClass.WTSUserName, out buffer, out strLen) && strLen > 1) { username = Marshal.PtrToStringAnsi(buffer); // don't need length as these are null terminated strings WTSFreeMemory(buffer); if (WTSQuerySessionInformation(IntPtr.Zero, cur_session, WTSInfoClass.WTSDomainName, out buffer, out strLen) && strLen > 1) { username = Marshal.PtrToStringAnsi(buffer) + "\\" + username; // prepend domain name WTSFreeMemory(buffer); } } return username; }
3、參考文檔