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 sys
I can't see that function exposed to .NET, but in C(++) it would be
SHGetKnownFolderPath(FOLDERID_UserProfiles, ...)
System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal)
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
}
}
}
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.
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);