Last active
August 3, 2025 09:57
-
-
Save level120/071ae65e2ec2d1f60485589383f5ee66 to your computer and use it in GitHub Desktop.
Get last logged username on windows
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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