.net 获取系统当前登录用户(管理员身份运行同样有效)

今天学习了下怎么用.Net获取系统当前登陆用户名,因为目前还没看到一篇比较完整的文章,所以整理了下也分享出来,最后附带参考文档,方便深究的童鞋继续学习。

一、知识点简单介绍

相信很多人第一直觉是使用.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

三、参考文档

扫描二维码关注公众号,回复: 6452591 查看本文章

猜你喜欢

转载自www.cnblogs.com/yokeqi/p/11016800.html
今日推荐