C# 獲取系統當前登錄用戶(管理員身份運行同樣有效)


今天學習下怎么用.Net獲取系統當前登陸用戶名,因為目前網上基本只有最簡單的方式,但以管理員身份運行的話就會獲取不到,所以特整理一下作為分享,最后附帶參考文檔,方便深究的童鞋繼續學習。

==========  原創作品    作者:Yokeqi    出處:博客園  ==========

一、知識點簡單介紹

相信很多人第一直覺是使用.net的環境變量。

Environment.UserName

但是可能很多人找我這篇文章是因為這個環境變量其實會受到管理員身份運行的影響,獲取到的是管理員的身份,而不是真實的當前登錄用戶。

這里的思路是利用WindowsApi進行獲取,經過各種查資料得到一個Api函數

[DllImport("Wtsapi32.dll")]
protected static extern bool WTSQuerySessionInformation(IntPtr hServer, int sessionId, WTSInfoClass wtsInfoClass, out IntPtr ppBuffer, out uint pBytesReturned);

二、具體實例演示如何實現

1. 引入API接口

[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 方法主要用於對非托管資源的釋放。

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
}
View Code

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;
        }
View Code

三、參考文檔


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM