Current username if account name has changed

I am trying to get the name of the currently logged in user in C # - not the account name that I could easily find in Environment.UserName. I would like to list folders in MyComputer, as explorer does. How can I do this or is there another way to get the correct username?

Thanks in advance.

+4
source share
3 answers

Try using:

System.Security.Principal.WindowsIdentity.GetCurrent().Name This should return the current user account and name.

If this does not work after changing the username, another method is to get the current SID of the user, and then find the username corresponding to this SID.

 using System.Security.Principal; string sid = WindowsIdentity.GetCurrent().Owner.ToString(); return new SecurityIdentifier(sid).Translate(typeof(NTAccount)).ToString(); 

Otherwise, take the SID and try to find the appropriate user either through WMI or through the registry. Instructions on how to do this manually are here: http://pcsupport.about.com/od/registry/ht/find-user-security-identifier.htm

If you can manually confirm that any of these methods returns a new username, then simply implements this in code using WMI calls or registry access.

+2
source

Use it

 string windowLoging = WindowsIdentity.GetCurrent().Name; 

or

 string windowsLogin = Page.User.Identity.Name; 

or

 string windowsLogin = Environment.GetEnvironmentVariable("USERNAME"); 
+1
source

@ damienc88 Your link leads me to a solution:

  SelectQuery query = new SelectQuery("Win32_UserAccount", string.Format("Domain='{0}'", Environment.MachineName)); ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); foreach (ManagementObject mObject in searcher.Get()) { Console.WriteLine((string)mObject["Name"] + "\t" + (string)mObject["FullName"]); } 

"Full Name" is the property I was looking for. Thank you very much. - Harald Pitro

0
source

Source: https://habr.com/ru/post/1488423/


All Articles