C# 获取系统当前登陆用户(管理员身份运行一样有效)

今天学习下怎么用.Net获取系统当前登录用户名,由于目前网上基本只有最简单的方式,但以管理员身份运行的话就会获取不到,因此特整理一下做为分享,最后附带参考文档,方便深究的童鞋继续学习。html

==========  原创做品    做者:Yokeqi    出处:博客园  ==========api

1、知识点简单介绍session

相信不少人第一直觉是使用.net的环境变量。dom

Environment.UserName

可是可能不少人找我这篇文章是由于这个环境变量其实会受到管理员身份运行的影响,获取到的是管理员的身份,而不是真实的当前登陆用户。ide

这里的思路是利用WindowsApi进行获取,通过各类查资料获得一个Api函数函数

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

2、具体实例演示如何实现学习

1. 引入API接口ui

[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 方法主要用于对非托管资源的释放。this

2. WTSInfoClass类定义spa

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

3、参考文档

相关文章
相关标签/搜索