简体   繁体   中英

Get Windows Current LoggedIn User in C# Daemon Service

I have a daemon service in.NetCore 3.1. It is executed by Windows TaskScheduler. It needs to capture the window's current logged-in username. How to do it? Tried few options-

  1. WindowsIdentity.GetCurrent().Name.
  2. Environment.UserName.

Both above are not giving logged-in username. When I execute the daemon service manually, then only they give the correct username.

WindowsIdentity.GetCurrent().Name -> It is always returning SYSTEM as username when daemon service is executed by TaskScheduler.

Environment.UserName -> It is always returning Windows Hostname as username when daemon service is executed by TaskScheduler.

Kindly suggest!

When you create a task, you can select which user account to run the application under. Just select a 'user' account rather than 'system', and either of the suggested methods will work.

在此处输入图像描述

As Damien mentioned in comments, the current user can be interpreted differently. No one needs to be logged in either.

You can try this way:

  1. Retrieves the session identifier of the console session

    [DllImport("kernel32.dll")]

    static extern uint WTSGetActiveConsoleSessionId ();

// obtain the currently active session id; every logged on user in the system has a unique session id

    uint dwSessionId = WTSGetActiveConsoleSessionId();
  1. How to retrieve username from session ID, see:

https://smbadiwe.github.io/post/track-activities-windows-service/

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