we can easily read the Windows Logon User name.
The WMI (Windows Media Instrumentation)
queries are very similar with the SQL queries.
The sample code below written in C# reads the logon user name.
using System.Management;Will return the Windows Logon User name. Many other WMI queries are available.
public static string logonUser()
{
string _user = string.Empty;
ConnectionOptions co = new ConnectionOptions();
System.Management.ManagementScope ms
= new System.Management.ManagementScope("\" + "localhost" + "rootcimv2", co);
System.Management.ObjectQuery oq =
new System.Management.ObjectQuery("SELECT * FROM Win32_ComputerSystem");
ManagementObjectSearcher query =
new ManagementObjectSearcher(ms, oq);
ManagementObjectCollection queryCollection;
queryCollection = query.Get();
foreach (ManagementObject mo in queryCollection)
{
_userl = mo["UserName"].ToString();
}
char[] charSeparators = new char[] { '' };
int deger = _user.Split(charSeparators, StringSplitOptions.None).Length;
_user= _user.Split(charSeparators, StringSplitOptions.None)[deger - 1];
return _user;
}
5 comments:
this is so complex
i think
System.Environment.UserName.ToString()
and
System.Environment.UserDomainName
is much simpler...
System.Environment.UserName.ToString()
Worked much better for me, too. Thanks.
System.Environment.User* only works if your program is running as the user. If you're running as System or some other service ID, UserName will return that, instead of the console user.
System.Environment.UserName.ToString() works thanks
Thanks a lot for this!
Much better then System.Environment that retrieves "System" if you are working with services!
Thanks again for this!
Post a Comment