获取每个用户的文件夹SpecialFolder.MyDocuments(Get SpecialFol

2019-09-28 16:09发布

我有我的机器上运行的Windows服务。 我怎样才能得到每个用户的我的文档文件夹?

例如:

对于Windows XP,我必须获取列表:

  • C:\的Documents and Settings \用户1 \我的文档
  • C:\的Documents and Settings \用户2 \我的文档
  • ...

对于Windows 10,我必须获取列表:

  • C:\用户\用户1 \文件\

  • C:\用户\用户2 \文件\

  • ...

我怎样才能得到这些名单?

Answer 1:

我会建议使用此解决方案 ,然后就列举(为每个用户)的文件夹。

// getUserProfilesPath() is a method from https://stackoverflow.com/a/41752173/3179310
string path = getUserProfilesPath();
// now use WMIC to get all users on the local machine
SelectQuery query = new SelectQuery("Win32_UserAccount");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject result in searcher.Get())
{
    // and check if their folder exists
    if(Directory.Exists(Path.Combine(path, result["Name"])))
    {
        // user folder exists so now check if it has Documents folder
        if(DirectoryExists(Path.Combine(path, result["Name"], "Documents")))
        {
            DirectoryInfo userDocuments = new DirectoryInfo(Path.Combine(path, result["Name"], "Documents"));
            // userDocuments is now a directory info of that user's documents folder
        }
    }
}


文章来源: Get SpecialFolder.MyDocuments folders of each user