GetUserProfileDirectory (userenv)
Last changed: -88.130.157.202

.
Summary
Retrieves the path to the root directory of the specified user's profile.

C# Signature:

[DllImport("userenv.dll", SetLastError=true, CharSet=CharSet.Auto)]
static extern bool GetUserProfileDirectory(IntPtr hToken, StringBuilder path, ref int dwSize);

VB Signature:

User-Defined Types:

None.

Notes:

A token to a user's process or session must be handed. Returns true if successful; otherwise, false.

To get a user session token per WTSQueryUserToken() you need the SE_TCB_NAME privilege that only LocalSystem has.

Tips & Tricks:

Sample Code:

[DllImport("userenv.dll", SetLastError=true, CharSet=CharSet.Auto)]
static extern bool GetUserProfileDirectory(IntPtr hToken, StringBuilder path, ref int dwSize);

string GetUserProfilePath(IntPtr hToken)
{
    // get size of profile path string
    int dwSize = 0;
    GetUserProfileDirectory(hToken, null, ref dwSize);

    // get profile path of user
    StringBuilder profilePath = new StringBuilder(dwSize);
    if (!GetUserProfileDirectory(hToken, profilePath, ref dwSize))
    { // could not retrieve profile directory
        Console.Error.WriteLine("Cannot retrieve profile path. Error: " + Marshal.GetLastWin32Error().ToString());
        return "";
    }

    return profilePath.ToString();        
}

Documentation