I went over most of the answers here and none of them gave me the right user name.
In my case I wanted to get the logged in user name, while running my app from a different user, like when shift+right click on a file and «Run as a different user».
The answers I tried gave me the ‘other’ username.
This blog post supplies a way to get the logged in user name, which works even in my scenario:
https://smbadiwe.github.io/post/track-activities-windows-service/
It uses Wtsapi
Edit: the essential code from the blog post, in case it ever disappears, is
Add this code to a class inheriting from ServiceBase
[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,
}
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;
}
If you don’t have one already, add a constructor to the class; and add this line to it:
CanHandleSessionChangeEvent = true;
EDIT:
Per comments requests, here’s how I get the session ID — which is the active console session ID:
[DllImport("kernel32.dll")]
private static extern uint WTSGetActiveConsoleSessionId();
var activeSessionId = WTSGetActiveConsoleSessionId();
if (activeSessionId == INVALID_SESSION_ID) //failed
{
logger.WriteLog("No session attached to console!");
}
I went over most of the answers here and none of them gave me the right user name.
In my case I wanted to get the logged in user name, while running my app from a different user, like when shift+right click on a file and «Run as a different user».
The answers I tried gave me the ‘other’ username.
This blog post supplies a way to get the logged in user name, which works even in my scenario:
https://smbadiwe.github.io/post/track-activities-windows-service/
It uses Wtsapi
Edit: the essential code from the blog post, in case it ever disappears, is
Add this code to a class inheriting from ServiceBase
[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,
}
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;
}
If you don’t have one already, add a constructor to the class; and add this line to it:
CanHandleSessionChangeEvent = true;
EDIT:
Per comments requests, here’s how I get the session ID — which is the active console session ID:
[DllImport("kernel32.dll")]
private static extern uint WTSGetActiveConsoleSessionId();
var activeSessionId = WTSGetActiveConsoleSessionId();
if (activeSessionId == INVALID_SESSION_ID) //failed
{
logger.WriteLog("No session attached to console!");
}
Getting the current Windows username is a common task in C# programming, especially in applications that interact with the operating system. There are several methods to retrieve the username, each with its own advantages and disadvantages. In this article, we will explore different ways to retrieve the Windows user name using C#.
Method 1: Environment.UserName
To get the Windows user name using the Environment.UserName
method in C#, you can follow the below steps:
Step 1
Create a new C# console application project in Visual Studio.
Step 2
Add the following code to the Main
method of the Program
class:
string userName = Environment.UserName;
Console.WriteLine("User name: " + userName);
Step 3
Run the application and you will see the Windows user name displayed in the console window.
using System;
namespace WindowsUserName
{
class Program
{
static void Main(string[] args)
{
string userName = Environment.UserName;
Console.WriteLine("User name: " + userName);
Console.ReadLine();
}
}
}
Output:
This code will retrieve the Windows user name using the Environment.UserName
method and display it in the console window.
Method 2: WindowsIdentity.GetCurrent().Name
To get the Windows user name in C# using the WindowsIdentity.GetCurrent().Name
method, follow these steps:
- Import the
System.Security.Principal
namespace at the beginning of your C# file:
using System.Security.Principal;
- Use the
WindowsIdentity.GetCurrent().Name
method to retrieve the current Windows user name:
string userName = WindowsIdentity.GetCurrent().Name;
Here are some additional examples of how to get the Windows user name using different methods:
- Using
Environment.UserName
:
string userName = Environment.UserName;
- Using
System.DirectoryServices.AccountManagement.UserPrincipal.Current.Name
:
using System.DirectoryServices.AccountManagement;
string userName = UserPrincipal.Current.Name;
- Using
System.Security.Principal.WindowsPrincipal
:
WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
string userName = principal.Identity.Name;
These are some of the ways you can get the Windows user name in C#.
Method 3: System.Security.Principal.WindowsPrincipal.Current.Identity.Name
To get the Windows user name in C# using System.Security.Principal.WindowsPrincipal.Current.Identity.Name
, follow these steps:
- First, you need to include the namespace
System.Security.Principal
in your C# code file.
using System.Security.Principal;
- Then, you can get the current Windows user name by accessing the
Name
property of theWindowsIdentity
object returned by theWindowsPrincipal.Current.Identity
property.
string userName = WindowsPrincipal.Current.Identity.Name;
Here is an example code snippet that demonstrates how to get the current Windows user name using System.Security.Principal.WindowsPrincipal.Current.Identity.Name
:
using System;
using System.Security.Principal;
class Program
{
static void Main(string[] args)
{
// Get the current Windows user name
string userName = WindowsPrincipal.Current.Identity.Name;
// Print the user name to the console
Console.WriteLine("Current Windows user name: " + userName);
}
}
This code will output the current Windows user name to the console.
Note that this method returns the user name in the format DOMAIN\Username
. If you only want the username without the domain name, you can use the Environment.UserName
property instead:
string userName = Environment.UserName;
This property returns only the username without the domain name.
Method 4: System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName
To retrieve the current Windows user name in C# using the System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName
method, you can follow these steps:
- First, add a reference to the
System.DirectoryServices.AccountManagement
namespace in your project.
using System.DirectoryServices.AccountManagement;
- Then, you can simply call the
UserPrincipal.Current.DisplayName
property to retrieve the display name of the current user.
string userName = UserPrincipal.Current.DisplayName;
Here’s a full example:
using System;
using System.DirectoryServices.AccountManagement;
namespace UserDisplayNameExample
{
class Program
{
static void Main(string[] args)
{
string userName = UserPrincipal.Current.DisplayName;
Console.WriteLine("Current user display name: " + userName);
}
}
}
Output:
Current user display name: John Doe
That’s it! This method is a simple and efficient way to retrieve the current Windows user name in C#.
- Remove From My Forums
-
Question
-
Hi,
How can we get Windows logged in user credential using C#.NET API?
Do we have any API to get the current User login and password ?
Thanx in advance,
yagnesh
Answers
-
You can get the current identity of the user under which the current thread is running (not necessarily the logged in user) using WindowsIdentity.GetCurrent(). Alternatively you can get the logged in user name via the Environment.UserName property. It is not guaranteed to be the user running the current process however.
There is no Windows API to get a user’s password as passwords aren’t stored in Windows. Instead Windows stores a one-way hashed version.
Michael Taylor — 4/9/08
http://p3net.mvps.org
-
You can get current credential of logged user using System.Net.CredentialCache.DefaultCredentials and also System.Net.CredentialCache.DefaultNetworkCredentials but from them you can’t read nothing usefull like username or password. You can create new credential by setting Username, Password and maybe Domain but reading is not posible and never will be.
-
I want to add to the previous answers.
In a web application, you need to invoke the following code to get the user identity of the active user on the current request —
Code Snippet
System.Web.HttpContext.Current.User.Identity
This is a little different from the case when you are not developing web applications, because under default settings the current windows user thats running a web application on the server is the IIS user account and not the actual user account associated with a particular request.-Sohan
MCTS, CSM
http://smsohan.blogspot.com
- Get current username in C++ on Windows
- Get current user name under Windows
- Get currently logged in user c
- WindowsIdentity.GetCurrent Method
- CMD – Get Current UserName in Windows
- Get current logged in user name command line (CMD)
Get current username in C++ on Windows
7 Answers. Use the Win32API GetUserName function. Example: #include
<windows.h> #include <Lmcons.h> char username [UNLEN+1]; DWORD username_len =
UNLEN+1; GetUserName (username, &username_len); +1, you can use GetUserNameEx
if you’d like to control the format of the username instead of what was
entered by the user.
char *userName = getenv("LOGNAME");
stringstream ss;
string userNameString;
ss << userName;
ss >> userNameString;
cout << "Username: " << userNameString << endl;
#include <windows.h>
#include <Lmcons.h>
char username[UNLEN+1];
DWORD username_len = UNLEN+1;
GetUserName(username, &username_len);
TCHAR username[UNLEN + 1];
DWORD size = UNLEN + 1;
GetUserName((TCHAR*)username, &size);
#include <iostream>
using namespace std;
#include <windows.h>
#include <Lmcons.h>
int main()
{
TCHAR name [ UNLEN + 1 ];
DWORD size = UNLEN + 1;
if (GetUserName( (TCHAR*)name, &size ))
wcout << L"Hello, " << name << L"!\n";
else
cout << "Hello, unnamed person!\n";
}
char * user = getenv("username");
cout << string(user) << endl;
string userStr = string(user);
Get current user name under Windows
How can I get the current users sign in name in Windows? What I have figured
out is the function. char* user_name; user_name=getenv («USERNAME»); but the
problem is that it gives. admin. but when I sign in to Windows, my user name
is «Sudip» and not «admin». c windows. Share. Improve this question.
char* user_name;
user_name=getenv("USERNAME");
admin
#include <windows.h>
#include <Lmcons.h>
char username[UNLEN+1];
DWORD username_len = UNLEN+1;
GetUserName(username, &username_len);
Get currently logged in user c
We can easily find current username in C# by using either by Environment class
or WindowsIdentity . 1. Environment.UserName. – Return username without domain
part. 1. System.Security.Principal.WindowsIdentity.GetCurrent ().Name. –
Return username with domain part : ‘DomainNameUsername’. You need to add
reference to System.Security
Environment.UserName
System.Security.Principal.WindowsIdentity.GetCurrent().Name
using System;
using System.Security.Principal;
namespace GetUserInfo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("UserName: " + Environment.UserName);
Console.WriteLine("IdentityName: " + WindowsIdentity.GetCurrent().Name);
}
}
}
WindowsIdentity.GetCurrent Method
Overloads. GetCurrent (TokenAccessLevels) Returns a WindowsIdentity object
that represents the current Windows user, using the specified desired token
access level. GetCurrent (Boolean) Returns a WindowsIdentity object that
represents the Windows identity for either the thread or the process,
depending on the value of the ifImpersonating
public:
static System::Security::Principal::WindowsIdentity ^ GetCurrent(System::Security::Principal::TokenAccessLevels desiredAccess);
public static System.Security.Principal.WindowsIdentity GetCurrent (System.Security.Principal.TokenAccessLevels desiredAccess);
static member GetCurrent : System.Security.Principal.TokenAccessLevels -> System.Security.Principal.WindowsIdentity
Public Shared Function GetCurrent (desiredAccess As TokenAccessLevels) As WindowsIdentity
public:
static System::Security::Principal::WindowsIdentity ^ GetCurrent(bool ifImpersonating);
public static System.Security.Principal.WindowsIdentity GetCurrent (bool ifImpersonating);
public static System.Security.Principal.WindowsIdentity? GetCurrent (bool ifImpersonating);
static member GetCurrent : bool -> System.Security.Principal.WindowsIdentity
Public Shared Function GetCurrent (ifImpersonating As Boolean) As WindowsIdentity
public:
static System::Security::Principal::WindowsIdentity ^ GetCurrent();
public static System.Security.Principal.WindowsIdentity GetCurrent ();
static member GetCurrent : unit -> System.Security.Principal.WindowsIdentity
Public Shared Function GetCurrent () As WindowsIdentity
IntPtr accountToken = WindowsIdentity::GetCurrent()->Token;
IntPtr accountToken = WindowsIdentity.GetCurrent().Token;
Console.WriteLine( "Token number is: " + accountToken.ToString());
Dim accountToken As IntPtr = WindowsIdentity.GetCurrent().Token
CMD – Get Current UserName in Windows
Using the whoami command, you can get the currently logged-in user in the
Windows system. The whoami command prints the username with the domain name.
whoami. The output of the above command in CMD to find the current username in
Windows is: C:\>whoami ShellPro\ShellGeek C:\>. You can also use PowerShell to
print the current username using …
echo %username%
$Env:USERNAME
PS D:\> $Env:USERNAME
ShellGeek
PS D:\>
whoami
C:\>whoami
ShellPro\ShellGeek
C:\>
PS D:\> whoami
PS D:\> whoami
ShellPro\ShellGeek
PS D:\>
Get current logged in user name command line (CMD)
This works on all releases of Windows OS(Windows XP, Server 2003, Windows
Vista and Windows 7). There is another command whoami which tells us the
domain name also. whoami. Example: c:\>whoami cmdline\administrator. Both of
these options to find user name can be useful in batch files to write code in
such a way that it works for every user.
echo %username%
whoami
c:\>whoami
cmdline\administrator