Skip to content

Instantly share code, notes, and snippets.

@level120
Last active August 3, 2025 09:57
Show Gist options
  • Select an option

  • Save level120/071ae65e2ec2d1f60485589383f5ee66 to your computer and use it in GitHub Desktop.

Select an option

Save level120/071ae65e2ec2d1f60485589383f5ee66 to your computer and use it in GitHub Desktop.
Get last logged username on windows
const string RegPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI";
const string DisplayNameKey = "LastLoggedOnDisplayName";
const string SamUserKey = "LastLoggedOnSAMUser";
Console.WriteLine($"Login User: {GetUserName()}");
public static string GetUserName()
{
var registryHive = RegistryHive.LocalMachine;
var registryView = Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32;
using var lastUserInfo = RegistryKey.OpenBaseKey(registryHive, registryView).OpenSubKey(RegPath);
if (lastUserInfo is null)
{
return Environment.UserName;
}
var displayName = (string)lastUserInfo.GetValue(DisplayNameKey);
var samName = ((string)lastUserInfo.GetValue(SamUserKey)).Replace(@".\", string.Empty);
return $"{displayName}({samName})";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment