25 November 2008

C# Read Windows Logon User Name in WMI

Using the namespace System.Management,
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;

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;
}
Will return the Windows Logon User name. Many other WMI queries are available.

5 comments:

Anonymous said...

this is so complex

i think

System.Environment.UserName.ToString()
and
System.Environment.UserDomainName

is much simpler...

Unknown said...

System.Environment.UserName.ToString()
Worked much better for me, too. Thanks.

Unknown said...

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.

Anonymous said...

System.Environment.UserName.ToString() works thanks

Pedro Carloto said...

Thanks a lot for this!

Much better then System.Environment that retrieves "System" if you are working with services!

Thanks again for this!