Search Unity

Question How would I find out the name of the system's currently logged in user?

Discussion in 'Scripting' started by Debunklelel, May 29, 2023.

  1. Debunklelel

    Debunklelel

    Joined:
    Mar 20, 2020
    Posts:
    2
    Okay so I'm looking for a way to capture the name of the currently logged in user the only solutions I've found so far are

    string userName = Environment.UserName;


    And

    string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;


    Which both produce syntax errors. First one gives CS0103 and the second one gives CS1069. So does anyone have any other solutions I could try?
     
  2. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,116
    Can you actually tell us the messages of the errors? Nobody knows the errors by their numbers. Numbers are issued as part of a compiler specification, they're not for every day use.

    As far as I can tell CS0103 is you attempting to use a field that doesn't exist. Which is definitely not how programming works. The other error I won't even comment, god knows what you're attempting to read there.

    The other thing is well, the environment that you are targeting. What you look for is not something that has anything to do with Unity, being platform-agnostic for the most part, so for such things you'd have to reach out to the system on your own.

    But what system? You need to specify is it Windows, is it something else... If it's Windows (and looks like it is) you most likely need to go through the system libraries, most likely kernel32.dll, which permanently binds your build to a specific version of Windows, because kernel32.dll might change without notice.
     
    Last edited: May 29, 2023
  3. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,116
    In fact, it's advapi32.dll and the function name is GetUserNameA.
    You can see what happens when a Unity game binds itself to such things and then a user changes Windows version HERE

    Sometimes it's mandatory, however, I don't judge you. Just make sure you understand the implications.
     
  4. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,116
    Here's example code, though I haven't tried it, this is assembled from the material I've gathered.

    Code (csharp):
    1. using System;
    2. using System.Text;
    3. using System.Runtime.InteropServices;
    4.  
    5. static public class WindowsUserNameExtraction {
    6.  
    7.   [DllImport("advapi32.dll")]
    8.   static extern bool GetUserName(StringBuilder lpBuffer, ref int nSize);
    9.  
    10.   static public string GetName() {
    11.     int size = 128;
    12.     var buffer = new StringBuilder(size);
    13.     GetUserName(buffer, ref size);
    14.     return buffer.ToString();
    15.   }
    16.  
    17. }

    To use this, try
    Code (csharp):
    1. Debug.Log(WindowsUserNameExtraction.GetName());