1

如何在 Windows 7 64 位系统中从 C# Windows 服务获取当前登录的用户名。

我正在使用以下在 32 位 Windows 中运行良好的代码:

ManagementObjectSearcher searcher = 
       new ManagementObjectSearcher("SELECT UserName from Win32_ComputerSystem");

ManagementObjectCollection collection = searcher.Get();

string username = 
       (string)collection.Cast<ManagementBaseObject>().First()["UserName"];

但不能在 64 位上运行。请建议

谢谢

4

2 回答 2

1

一个简单的解决方案是使用通常包含登录用户名的 Environment.UserName。

在某些情况下,服务正在运行,没有用户登录并且 Environment.UserName 为空,或者 env.UserName 为空。变量因某种奇怪的原因被删除。您可以使该变量在这种情况下是必需的。

System.Security.Principal.WindowsIdentity.GetCurrent() 在比 Environment.UserName 更多的情况下可能为空,因此请注意在检查 System.Security.Principal.WindowsIdentity 之前不要调用 System.Security.Principal.WindowsIdentity.GetCurrent().Name .GetCurrent() 确实存在。

如果您想弄清楚当前登录的终端服务会话,您可以使用以下类:

public class TerminalServices {
    [DllImport("wtsapi32.dll", SetLastError = true)] 
    static extern IntPtr WTSOpenServer([MarshalAs(UnmanagedType.LPStr)] String pServerName);

    [DllImport("wtsapi32.dll")] 
    static extern void WTSCloseServer(IntPtr hServer);

    [DllImport("wtsapi32.dll", SetLastError=true)] 
    static extern Int32 WTSEnumerateSessions(IntPtr hServer, [MarshalAs(UnmanagedType.U4)] Int32 Reserved, [MarshalAs(UnmanagedType.U4)] Int32 Version, ref IntPtr ppSessionInfo, [MarshalAs(UnmanagedType.U4)] ref Int32 pCount);

    [DllImport("wtsapi32.dll")]
    static extern void WTSFreeMemory(IntPtr pMemory);

    [StructLayout(LayoutKind.Sequential)] 
    private struct WTS_SESSION_INFO {
        public Int32 SessionID;

        [MarshalAs(UnmanagedType.LPStr)] 
        public String pWinStationName;

        public WTS_CONNECTSTATE_CLASS State;
    }

    public enum WTS_CONNECTSTATE_CLASS {
        WTSActive,
        WTSConnected,
        WTSConnectQuery,
        WTSShadow,
        WTSDisconnected,
        WTSIdle,
        WTSListen,
        WTSReset,
        WTSDown,
        WTSInit
    } 

    public static IntPtr OpenServer(String Name) {
        IntPtr server = WTSOpenServer(Name);
        return server;
    }

    public static void CloseServer(IntPtr ServerHandle) {
        WTSCloseServer(ServerHandle);
    }

    public static List<Session> ListSessions(String ServerName) {
        var ret = new List<Session>();
        var server = OpenServer(ServerName);

        try {
            IntPtr ppSessionInfo = IntPtr.Zero;
            Int32 count = 0;
            Int32 retval = WTSEnumerateSessions(server, 0, 1, ref ppSessionInfo, ref count);
            Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO));
            Int64 current = (int) ppSessionInfo;

            if (retval != 0) {
                for (int i=0; i<count; i++) {
                    WTS_SESSION_INFO si = (WTS_SESSION_INFO) Marshal.PtrToStructure((System.IntPtr) current, typeof(WTS_SESSION_INFO));
                    current += dataSize;

                    ret.Add(new Session { Id = si.SessionID, State = si.State.ToString(), Type = si.pWinStationName });
                }

                WTSFreeMemory(ppSessionInfo);
            }
        } finally {
            CloseServer(server);
        }

        return ret;
    }
}

public class Session {
    public int Id {
        get;
        set;
    }

    public string State {
        get;
        set;
    }

    public string Type {
        get;
        set;
    }
}

TerminalServices.ListSessions 将告诉您有多少用户以及哪些用户登录到该终端。

于 2013-09-05T11:43:45.120 回答
-1

使用它来获取当前登录的用户。如果有效,请将其标记为答案。

System.Security.Principal.WindowsIdentity.GetCurrent().Name;
于 2013-09-05T11:31:46.670 回答