other methods
public string GetUserName() { return System.Environment.UserName;
Using WMI (Windows Management Instrumentation):
using System.Management;
public string GetUserName() { ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT UserName FROM Win32_ComputerSystem"); string user = string.Empty; foreach (ManagementObject queryObj in searcher.Get()) { user = Convert.ToString(queryObj["UserName"]); } return user; }
Unmanaged Method: GetUserName API Link
using System.Runtime.InteropServices; public string GetUserName() { byte[] user = new byte[256]; Int32[] len = new Int32[1]; len[0] = 256; GetUserName(user, len); return (System.Text.Encoding.ASCII.GetString(user)); } [DllImport("Advapi32.dll", EntryPoint = "GetUserName", ExactSpelling = false, SetLastError = true)] static extern bool GetUserName([MarshalAs(UnmanagedType.LPArray)] byte[] lpBuffer, [MarshalAs(UnmanagedType.LPArray)] Int32[] nSize);
Using WindowsIdentity
using System.Security.Principal; public string GetUserName() { return( WindowsIdentity.GetCurrent().Name); }
source share