一个简单的解决方案是使用通常包含登录用户名的 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 将告诉您有多少用户以及哪些用户登录到该终端。