Obtaining path of users directory

前端 未结 5 605
小蘑菇
小蘑菇 2021-01-18 18:43

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

相关标签:
5条回答
  • 2021-01-18 18:49

    I can't see that function exposed to .NET, but in C(++) it would be

    SHGetKnownFolderPath(FOLDERID_UserProfiles, ...)
    
    0 讨论(0)
  • 2021-01-18 18:51

    System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal)

    0 讨论(0)
  • 2021-01-18 18:55

    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
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-18 19:03

    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.

    0 讨论(0)
  • 2021-01-18 19:11

    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);
    
    0 讨论(0)
提交回复
热议问题