How to get path of Users folder from windows service on MS Vista? I think about path of C:\Users directory, but it may be different location depend on system localization.
-
Do you want the particular home path for a particular user? There's no guarantee that all users would have their home folders in the same location. (Remote home folders, for instance.) – Edward Thomson Jan 06 '12 at 21:29
6 Answers
Take a look at the Environment.SpecialFolder Enumeration, e.g.
Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory);
Adjust for the special folder you want. However, in reading another post found here, it looks like you may need to do a little manipulation of the string if you want exactly c:\users instead of c:\users\public, for example.

- 1
- 1

- 31,652
- 27
- 127
- 172
System.Environment.SpecialFolder will give you access to all these folders that you want, such as My Documents, Etc..
If you use the UserProfile SpecialFolder, that should give you the path to your profile under Users.
string userPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

- 20,682
- 14
- 79
- 108
The best way as @Neil pointed out is to use SHGetKnownFolderPath()
with the FOLDERID_UserProfiles
. However, c# doesn't have that. But, it's not that hard to invoke it:
using System;
using System.Runtime.InteropServices;
namespace SOExample
{
public class Main
{
[DllImport("shell32.dll")]
static extern int SHGetKnownFolderPath([MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint dwFlags, IntPtr hToken, out IntPtr pszPath);
private static string getUserProfilesPath()
{
// https://msdn.microsoft.com/en-us/library/windows/desktop/dd378457(v=vs.85).aspx#folderid_userprofiles
Guid UserProfilesGuid = new Guid("0762D272-C50A-4BB0-A382-697DCD729B80");
IntPtr pPath;
SHGetKnownFolderPath(UserProfilesGuid, 0, IntPtr.Zero, out pPath);
string path = System.Runtime.InteropServices.Marshal.PtrToStringUni(pPath);
System.Runtime.InteropServices.Marshal.FreeCoTaskMem(pPath);
return path;
}
static void Main(string[] args)
{
string path = getUserProfilesPath(); // C:\Users
}
}
}

- 10,150
- 3
- 52
- 76
I can't see that function exposed to .NET, but in C(++) it would be
SHGetKnownFolderPath(FOLDERID_UserProfiles, ...)

- 54,642
- 8
- 60
- 72
I think the simplest way to do this iv via:
var usersFolder = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile));
Now I am not a Windows specialist, but I think that always goes to the root folder where all profiles are stored, if a user has a roaming profile on some server that he's loaded via the network drive then you're out of luck I guess unless you're on the domain controller and you query the profile for the roaming path.

- 3,867
- 27
- 36
System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal)

- 4,466
- 24
- 21