How to Get the Currently-Logged Username from a Windows Service in .Net

How do I get the current username in .NET using C#?

Option A)

string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
  • Returns: NetworkName\Username
  • Gets the user's Windows logon name.
  • Details: https://learn.microsoft.com/en-us/dotnet/api/system.security.principal.windowsidentity

Option B)

string userName = Environment.UserName
  • Returns: Username
  • Gets the user name of the person who is associated with the current thread.
  • Details: https://learn.microsoft.com/en-us/dotnet/api/system.environment.username

From WindowsService how can I find currently logged in user from C#?

1) Cassia should be able to give you a list of currently logged in users including RDC.

foreach (ITerminalServicesSession sess in new TerminalServicesManager().GetSessions())
{
// sess.SessionId
// sess.UserName
}

2) WMI (SO answer)

Select * from Win32_LogonSession

3) PInvoke to WTSEnumerateSessions

4) Enumerate all instances of "explorer.exe" and get the owner using PInvoke (OpenProcessHandle).

Process[] processes = Process.GetProcessesByName("explorer");

This is a bit hacky. WMI can also be used for this.

It might be a good idea to set winmgmt as a dependency for your service if you decided to go with solution that uses WMI.

How to get current windows username from windows service in multiuser environment using .NET

I solve it by executing powershell command "quser" in my WPF application which returns all the logged in users then I am iterating to find session id in which the application is running with user session id and then retrieving his name. below is the function which fetch the username by passing his session id

 private string GetUserName(int SessionId)
{
try
{
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();

Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript("Quser");
pipeline.Commands.Add("Out-String");

Collection<PSObject> results = pipeline.Invoke();

runspace.Close();

StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}

foreach (string User in stringBuilder.ToString().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).Skip(1))
{
string[] UserAttributes = User.Split(new string[]{" "},StringSplitOptions.RemoveEmptyEntries);
if (int.Parse(UserAttributes[2].Trim()) == SessionId)
{
return UserAttributes[0].Replace(">", string.Empty).Trim();
}
}

return stringBuilder.ToString();
}
catch (Exception ex)
{
}

return string.Empty;
}

the function can be called by

string CurrentUser = GetUserName(Process.GetCurrentProcess().SessionId);

How to get currently Windows logged User Credentials?

You can get the current Windows user credentials by using the System.Net.CredentialCache.DefaultCredentials static property.

You won't be able to get the password as that would be a major security hole. You should be able to get everything else you want out of that, however.

Windows service: Get username when user log on

Finally I got a solution. In the windows service method, there is the session id provided. So with this session id we can execute a powershell command 'quser' and get the current user, who login/logoff on the server. Seen here: How to get current windows username from windows service in multiuser environment using .NET

So this is the function, which we need to create:

private string GetUsername(int sessionID)
{
try
{
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();

Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript("Quser");
pipeline.Commands.Add("Out-String");

Collection<PSObject> results = pipeline.Invoke();

runspace.Close();

StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}

foreach (string User in stringBuilder.ToString().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).Skip(1))
{
string[] UserAttributes = User.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);

if (UserAttributes.Length == 6)
{
if (int.Parse(UserAttributes[1].Trim()) == sessionID)
{
return UserAttributes[0].Replace(">", string.Empty).Trim();
}
}
else
{
if (int.Parse(UserAttributes[2].Trim()) == sessionID)
{
return UserAttributes[0].Replace(">", string.Empty).Trim();
}
}
}

}
catch (Exception exp)
{
// Error handling
}

return "Undefined";
}

And this is the windows service function:

protected override void OnSessionChange(SessionChangeDescription changeDescription)
{
try
{
switch (changeDescription.Reason)
{
case SessionChangeReason.SessionLogon:
string user = GetUsername(changeDescription.SessionId);

WriteLog("Logon - Program continue" + Environment.NewLine +
"User: " + user + Environment.NewLine + "Sessionid: " + changeDescription.SessionId);

//.....


Related Topics



Leave a reply



Submit