Search code examples
.netrunas

How can a program (.NET) tell if it is being run as a different user?


Is there a way to detect from my .NET program whether it is being run as the desktop user normally or being run as a different user using the "run as a different user" menu option/runas command?


Solution

  • Getting the user which ran the program is easier, you can use Environment.UserName or System.Security.Principal.WindowsIdentity.GetCurrent().Name.
    Links to the difference between them are located below...

    Now, getting the logged in user is a little more tricky.
    I use the following method (I think I found it here in SO a while back). What it does is check who is the owner of the explorer.exe process (which is the logged in user):

    private string GetExplorerUser()
    {
        var query = new ObjectQuery(
            "SELECT * FROM Win32_Process WHERE Name = 'explorer.exe'");
    
        var explorerProcesses = new ManagementObjectSearcher(query).Get();
    
        foreach (ManagementObject mo in explorerProcesses)
        {
           String[] ownerInfo = new string[2];
           mo.InvokeMethod("GetOwner", (object[])ownerInfo);
    
           return String.Concat(ownerInfo[1], @"\", ownerInfo[0]);
        }
    
        return string.Empty;
    }
    

    The method above requires the System.Managment dll

    Update: Method above works fine, based on OP's comments - added another option :

    Getting first username from Win32_ComputerSystem:

     ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
     ManagementObjectCollection collection = searcher.Get();
     string username = (string)collection.Cast<ManagementBaseObject>().First()["UserName"];