Reputation: 54
I am trying to get "current active user account name" (Windows user).
For that I have tried the below mentioned code and I get the "current active user account name", but this code first get all users list and then filters (get) the "current active user name".
Now, I am trying to get "current active user account name" (Windows user) but without a for
loop and I tried to get help (research) in Microsoft Developer Documentation but I could not able to find helpful resources.
SelectQuery userListQuery = new SelectQuery("Win32_UserAccount");
ManagementObjectSearcher userSearcher = new ManagementObjectSearcher(userListQuery);
foreach (ManagementObject envVar in userSearcher.Get())
{
// get sid string from username (for to acsess user's current_user registry key)
NTAccount userAccount = new NTAccount(envVar["Name"].ToString());
SecurityIdentifier sid = (SecurityIdentifier)userAccount.Translate(typeof(SecurityIdentifier));
string sidString = sid.ToString();
File.AppendAllText("c:\\outs\\log.txt", " ---- user account ----" + userAccount + "\n\n");
File.AppendAllText("c:\\outs\\log.txt", " ---- sid string ----" + sidString + "\n\n");
}
Upvotes: 0
Views: 454
Reputation: 54
I've solved my problem using:
var searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
var collection = searcher.Get();
string username = (string)collection.Cast<ManagementBaseObject>().First()["UserName"];
Upvotes: 1