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
5 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
- 30,786
- 27
- 122
- 170
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);
- 19,633
- 13
- 75
- 105
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
}
}
}
- 9,130
- 3
- 48
- 75
I can't see that function exposed to .NET, but in C(++) it would be
SHGetKnownFolderPath(FOLDERID_UserProfiles, ...)
- 52,766
- 8
- 57
- 71
System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal)
- 4,361
- 22
- 21