c# - 如何从 SessionID 获取 Windows 用户名?

标签 c# windows sessionid

C# 中是否有从给定 session ID 中检索用户名的方法?
(系统上运行的任何 session )

Win API 函数 WTSQuerySessionInformation执行此操作,但我正在 C# 中搜索此功能。

最佳答案

似乎没有 .NET 集成方法。
所以这是当前的解决方案,使用 Windows 终端服务 API:

    [DllImport("Wtsapi32.dll")]
    private static extern bool WTSQuerySessionInformation(IntPtr hServer, int sessionId, WtsInfoClass wtsInfoClass, out System.IntPtr ppBuffer, out int pBytesReturned);
    [DllImport("Wtsapi32.dll")]
    private static extern void WTSFreeMemory(IntPtr pointer);

    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,
    }

    public static string GetUsernameBySessionId(int sessionId, bool prependDomain) {
        IntPtr buffer;
        int strLen;
        string username = "SYSTEM";
        if (WTSQuerySessionInformation(IntPtr.Zero, sessionId, WtsInfoClass.WTSUserName, out buffer, out strLen) && strLen > 1) {
            username = Marshal.PtrToStringAnsi(buffer);
            WTSFreeMemory(buffer);
            if (prependDomain) {
                if (WTSQuerySessionInformation(IntPtr.Zero, sessionId, WtsInfoClass.WTSDomainName, out buffer, out strLen) && strLen > 1) {
                    username = Marshal.PtrToStringAnsi(buffer) + "\\" + username;
                    WTSFreeMemory(buffer);
                }
            }
        }
        return username;
    }

关于c# - 如何从 SessionID 获取 Windows 用户名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19487541/

相关文章:

c# - 使用 WiX 工具集编辑文件

c# - Expression.Coalesce 的转换参数是做什么用的?

c# - 在批处理文件中包含一个批处理文件

linux - 什么是 Linux 命令 wc -l 的 windows 等价物?

windows - 如何使用 GDI 函数在 OpenGL 使用的 DC 上绘图?

java - NoSuchSessionException session ID 为空。调用 quit() 后使用 WebDriver?并行运行 java 测试时

c# - 计算时间长

eclipse - 带插件的可移植 Eclipse Juno

java - 网络服务器中的 session

tomcat - 无法使用 %S 配置 tomcat 访问日志 session ID