Search code examples
file-iodirectoryfinder

automatically get computer user for a directory


I made a password saving program that saves to a file in a specific directory

static String fly = "C:\\Users\\tomtom\\Documents\\AlternativePorjectDirectory\\accounts";

                          user--/\/\/\
                                ||||||

but everytime I give this softwar to someone I have to ask them for their user, rewrite the software then, export to usb and give it to them. automatically finding the computer user will make it so I can share this program with everyone.
what I want it to look like

static String fly = "C:\\Users\\"+C:User+"\\Documents\\AlternativePorjectDirectory\\accounts";

so that computer user= C:User

I am very new to programming so may have to be specific


Solution

  • You actually don't need to do that, and since the user folder isn't always C:\Users\, there's a better way.

    %USERPROFILE% is an environment variable that will always be equal to the user folder, for example C:\Users\SomeGuy, or on an XP system, C:\Documents and Settings\SomeOtherGuy.

    Just:

    DWORD nSize = MAX_PATH;
    CHAR* lpBuffer = new CHAR[nSize];
    GetEnvironmentVariableA("USERPROFILE",lpBuffer,nSize);
    static String fly = lpBuffer+"\\Documents\\AlternativePorjectDirectory\\accounts";