从获得的SessionID Windows用户名 [英] Get Windows user name from SessionID

查看:721
本文介绍了从获得的SessionID Windows用户名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有在C#中的方法从给定的会话ID检索用户名?结果
(在系统上运行任何会话)

Is there a method in C# to retrieve the user name from a given session id?
(any session running on the system)

该赢API函数<一个href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/aa383838%28v=vs.85%29.aspx\"><$c$c>WTSQuerySessionInformation做到这一点,但我在寻找这个funcationality在C#。

The Win API function WTSQuerySessionInformation does this, but I'm searching for this funcationality in C#.

推荐答案

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

There seems to be no .NET integrated method for this.
So this is the current solution, using Windows Terminal services 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;
    }

这篇关于从获得的SessionID Windows用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆