【问题标题】:How to get Windows user name from SessionID?如何从 SessionID 获取 Windows 用户名?
【发布时间】:2013-10-29 12:47:47
【问题描述】:

C# 中有没有一种方法可以从给定的会话 id 中检索用户名?
(系统上运行的任何会话)

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

【问题讨论】:

  • @ThirdBattleOfPanipat:这比 WTSQuerySessionInformation 更复杂 - 而且它也是 Win API,而不是普通的 C#。那么.NET框架中没有方法吗?
  • 没有与 ASP.Net 会话相关联的“用户名”的概念......您想要获得的“用户名”究竟是什么?
  • @AlexeiLevenkov:这是由桌面联盟使用的,这里没有 ASP。
  • .NET 专注于最终用户和 Web 应用程序,因此作为一般规则,它排除了更核心的系统管理功能。如果它包含终端服务 API,我会感到惊讶。

标签: c# windows sessionid


【解决方案1】:

似乎没有针对此的 .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;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-05
    • 2013-05-30
    • 2019-01-17
    • 2010-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多