.net 获取用户目录的路径

t1rydlwq  于 2023-08-08  发布在  .NET
关注(0)|答案(6)|浏览(162)

如何从MS Vista上的Windows服务中获取用户文件夹的路径?我想的是C:\Users目录的路径,但它可能是不同的位置,取决于系统本地化。

qqrboqgw

qqrboqgw1#

看看Environment.SpecialFolder Enumeration,例如

  1. Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory);

字符串
调整到所需的特殊文件夹。然而,在阅读另一篇文章发现here,看起来你可能需要做一点操作的字符串,如果你想确切地 c:\users 而不是 c:\users\public,例如。

vyu0f0g1

vyu0f0g12#

System.Environment.SpecialFolder将给予您访问所需的所有这些文件夹,如“我的文档”等。
如果您使用UserProfile SpecialFolder,则会在Users下给予您的配置文件的路径。

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

字符串

py49o6xq

py49o6xq3#

正如@Neil指出的,最好的方法是将SHGetKnownFolderPath()FOLDERID_UserProfiles一起使用。但是C#却没有这个。但是,调用它并不难:

  1. using System;
  2. using System.Runtime.InteropServices;
  3. namespace SOExample
  4. {
  5. public class Main
  6. {
  7. [DllImport("shell32.dll")]
  8. static extern int SHGetKnownFolderPath([MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint dwFlags, IntPtr hToken, out IntPtr pszPath);
  9. private static string getUserProfilesPath()
  10. {
  11. // https://msdn.microsoft.com/en-us/library/windows/desktop/dd378457(v=vs.85).aspx#folderid_userprofiles
  12. Guid UserProfilesGuid = new Guid("0762D272-C50A-4BB0-A382-697DCD729B80");
  13. IntPtr pPath;
  14. SHGetKnownFolderPath(UserProfilesGuid, 0, IntPtr.Zero, out pPath);
  15. string path = System.Runtime.InteropServices.Marshal.PtrToStringUni(pPath);
  16. System.Runtime.InteropServices.Marshal.FreeCoTaskMem(pPath);
  17. return path;
  18. }
  19. static void Main(string[] args)
  20. {
  21. string path = getUserProfilesPath(); // C:\Users
  22. }
  23. }
  24. }

字符串

展开查看全部
zbdgwd5y

zbdgwd5y4#

我看不到该函数暴露给.NET,但在C(++)中,它将是

  1. SHGetKnownFolderPath(FOLDERID_UserProfiles, ...)

字符串

b5lpy0ml

b5lpy0ml5#

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

vi4fp9gy

vi4fp9gy6#

我认为最简单的方法是通过:

  1. var usersFolder = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile));

字符串
现在我不是一个WindowsMaven,但我认为它总是会转到存储所有配置文件的根文件夹,如果用户在某个服务器上有一个漫游配置文件,他通过网络驱动器加载,那么你就不走运了,我想除非你在域控制器上,你查询漫游路径的配置文件。

相关问题