How to get username C#


Is it possible to somehow get the username under which the login was made, if the application is launched under a different name?

Those. the user ivanov logs in (logs in), starts my application using the credentials (login and password) of the user petrov. Is it possible to somehow find out what exactly is ivanov.




give the same result – petrov.


Here is an example that gets the login of the user who is logged in.

private static string _username;

static void Main(string[] args)
    foreach (var p in Process.GetProcessesByName("explorer"))
        _username = GetProcessOwner(p.Id);

    // remove the domain part from the username
    var usernameParts = _username.Split('\\');

    _username = usernameParts[usernameParts.Length - 1];


public static string GetProcessOwner(int processId)
    var query = "Select * From Win32_Process Where ProcessID = " + processId;
    ManagementObjectCollection processList;

    using (var searcher = new ManagementObjectSearcher(query))
        processList = searcher.Get();

    foreach (var mo in processList.OfType<ManagementObject>())
        object[] argList = { string.Empty, string.Empty };
        var returnVal = Convert.ToInt32(mo.InvokeMethod("GetOwner", argList));

        if (returnVal == 0)
            // return DOMAIN\user
            return argList[1] + "\\" + argList[0];

    return "NO OWNER";
Scroll to Top