70

I have a Windows service which needs the currently logged username. I tried System.Environment.UserName, Windows identity and Windows form authentication, but all are returning "System" as the user my service is running as has system privileges. Is there a way to get the currently logged in username without changing my service account type?

4

9 Answers 9

95

This is a WMI query to get the user name:

ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
ManagementObjectCollection collection = searcher.Get();
string username = (string)collection.Cast<ManagementBaseObject>().First()["UserName"];

You will need to add System.Management under References manually.

5
  • 16
    People keep forgetting that the usual ways to "get" a username wont work when running a service because of the System Accounts... +1 for being the only answer to take this into account
    – amartin94
    Oct 18, 2015 at 18:50
  • 14
    I realize this question is really old, but I found it while Googling the same issue. While this answer is indeed correct, keep in mind, as @xanblax said in his answer, this WMI query will not work in a remote (RDP) session. Just wanted to point that out, and make it more visible, in case anyone else reads this in the future. Oct 12, 2016 at 23:07
  • 1
    Old answers are still useful. I stumbled across this now, August 2018. Aug 3, 2018 at 18:32
  • @Tapas Can u suggest how it can be used for a standard user?
    – Rupsingh
    Jan 25, 2020 at 9:25
  • Works fine in my service application running under a system account in Windows 10 20H2. Thanks!
    – Nate
    Apr 15, 2021 at 7:37
33

If you are in a network of users, then the username will be different:

Environment.UserName

Will Display format : 'Username', rather than

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

Will Display format : 'NetworkName\Username'

Choose the format you want.

3
  • 1
    just what i was looking for !
    – thedrs
    Mar 22, 2015 at 17:55
  • 40
    That totally doesn't answer the question. When your application is running as a service, both of those calls will return the service account name. Sep 19, 2015 at 21:03
  • 4
    it will return current service user, not user
    – Mahdi
    Feb 25, 2017 at 5:43
22

ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem") solution worked fine for me. BUT it does not work if the service is started over a Remote Desktop Connection. To work around this, we can ask for the username of the owner of an interactive process that always is running on a PC: explorer.exe. This way, we always get the currently Windows logged-in username from our Windows service:

foreach (System.Management.ManagementObject Process in Processes.Get())
{
    if (Process["ExecutablePath"] != null && 
        System.IO.Path.GetFileName(Process["ExecutablePath"].ToString()).ToLower() == "explorer.exe" )
    {
        string[] OwnerInfo = new string[2];
        Process.InvokeMethod("GetOwner", (object[])OwnerInfo);

        Console.WriteLine(string.Format("Windows Logged-in Interactive UserName={0}", OwnerInfo[0]));

        break;
    }
}
5
  • 4
    I wanted to use this answer, but I couldn't find the class Processes. Jan 25, 2017 at 16:15
  • This doesn't work if multiple users are logged in at once (e.g. in Windows 10 when you switch to another user) as one instance of explorer.exe is running for each user.
    – Vitani
    Jun 18, 2019 at 13:48
  • It should be the following: ManagementObjectSearcher Processes = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Process");
    – ilCosmico
    Feb 7, 2020 at 10:08
  • to make sure I was getting the correct copy of explorer.exe, I got the current process and took the session ID from that, then I compared that to the SessionID property value from the explorer.exe I found and then got the user information from that one. Apr 25 at 22:45
  • Of course a Windows Service might be in a session without a UI or without explorer.exe running in it's session, so you might have to doing some other way, but I am using this in a windows desktop application and it is working great. Apr 25 at 22:52
6

Modified code of Tapas's answer:

Dim searcher As New ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem")
Dim collection As ManagementObjectCollection = searcher.[Get]()
Dim username As String
For Each oReturn As ManagementObject In collection
    username = oReturn("UserName")
Next
2

Just in case someone is looking for user Display Name as opposed to User Name, like me.

Here's the treat :

System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName.

Add Reference to System.DirectoryServices.AccountManagement in your project.

1
  • 2
    When I try this, I get the error "Unable to cast object of type 'System.DirectoryServices.AccountManagement.GroupPrincipal' to type 'System.DirectoryServices.AccountManagement.UserPrincipal'." May 2, 2019 at 15:30
1

Try WindowsIdentity.GetCurrent(). You need to add reference to System.Security.Principal

1
  • 13
    I think this will return the user that the service is running as, not all interactive users as seen from the service running under a system account. Mar 7, 2011 at 11:40
1

You can also try

System.Environment.GetEnvironmentVariable("UserName");
2
  • 1
    What will that display? Domain\Username or just Username? Sep 10, 2014 at 15:24
  • @SearchForKnowledge: It just returns Username - It is equivalent of using the property 'Environment.UserName' Feb 9, 2018 at 10:47
0

Completing the answer from @xanblax

private static string getUserName()
{
    SelectQuery query = new SelectQuery(@"Select * from Win32_Process");
    using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
    {
       foreach (System.Management.ManagementObject Process in searcher.Get())
        {
            if (Process["ExecutablePath"] != null && string.Equals(Path.GetFileName(Process["ExecutablePath"].ToString()), "explorer.exe", StringComparison.OrdinalIgnoreCase))
            {
                string[] OwnerInfo = new string[2];
                Process.InvokeMethod("GetOwner", (object[])OwnerInfo);
                 return OwnerInfo[0];
            }
        }
    }

    return "";
}
0

Answer for Windows Service:

You can get it from the sessionId of a currently logged-in user. First, you have to add following P/INVOKE script in your code class:

[DllImport("Wtsapi32.dll")]
private static extern bool WTSQuerySessionInformation(IntPtr hServer, int sessionId, WtsInfoClass wtsInfoClass, out IntPtr ppBuffer, out int pBytesReturned);
[DllImport("Wtsapi32.dll")]
private static extern void WTSFreeMemory(IntPtr pointer);
 
private enum WtsInfoClass
{
    WTSUserName = 5, 
    WTSDomainName = 7,
}

[DllImport("Kernel32.dll", SetLastError = true)]
static extern int WTSGetActiveConsoleSessionId();

Then, add this method:

private static string GetUsername(int sessionId, bool prependDomain = true)
{
    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;
}

Finally, call the method like this:

int sessionId = WTSGetActiveConsoleSessionId();
string username = GetUsername(sessionId); // Gives 'Domain\Username'

Source links:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.