简体   繁体   中英

Get windows username in c# windows service in 64-bit Windows 7?

How to get the current logged in username from C# Windows service in Windows 7 64-bit system.

I'm using the following code which works fine in 32-bit Windows:

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

ManagementObjectCollection collection = searcher.Get();

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

But not run on 64 bit. please suggest

Thanks

A simple solution is to use Environment.UserName that normally contains the logged-on username.

There is cases where the service is running, no user logged-on and Environment.UserName is null or in cases where the env. variable was removed for some odd reason. You can make this variable required for that cases.

System.Security.Principal.WindowsIdentity.GetCurrent() may be null in more scenarios than Environment.UserName so be aware to not call System.Security.Principal.WindowsIdentity.GetCurrent().Name before checking that System.Security.Principal.WindowsIdentity.GetCurrent() really exists.

In case you want to figure out the current logged-on terminal services sessions you can make use of the following class:

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 will tell you how many users and what users are logged on into that terminal.

Use this to get current logged on user. Mark it as answer if it works.

System.Security.Principal.WindowsIdentity.GetCurrent().Name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM