2012-01-06 129 views
5

如何從MS Windows Vista上的windows服務獲取用戶文件夾路徑? 我認爲路徑爲C:\ Users目錄,但它可能是不同的位置取決於系統本地化。獲取用戶目錄路徑

+0

您是否想要特定用戶的特定主路徑?不能保證所有用戶的主文件夾都位於同一位置。 (例如遠程家庭文件夾。) – 2012-01-06 21:29:51

回答

11

看看Environment.SpecialFolder Enumeration,例如

Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory); 

調整你想要的特殊文件夾。但是,在閱讀另一篇帖子here時,看起來您可能需要對字符串進行一些操作,例如,如果您確切地想要使用c:\ users而不是c:\ users \ public

7

System.Environment.SpecialFolder會給你訪問到你希望所有這些文件夾,如我的文檔,等等。

如果您使用的用戶配置SpecialFolder,應該給你的路徑,您的配置文件下用戶。

string userPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); 
0

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

1

我不能看到該函數暴露於.NET,但在C(++)將是

SHGetKnownFolderPath(FOLDERID_UserProfiles, ...) 
2

@Neil指出的最好方法是使用SHGetKnownFolderPath()FOLDERID_UserProfiles。但是,c#沒有。但是,調用它並不困難:

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 
     } 
    } 
}