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

时间:2017-07-06 09:47:35

标签: c# .net windows service

我的计算机上运行了一个Windows服务。如何获取每个用户的MyDocuments文件夹?

例如:

对于Windows XP,我必须得到列表:

  • C:\ Documents and Settings \ User1 \ My Documents
  • C:\ Documents and Settings \ User2 \ My Documents
  • ...

对于Windows 10,我必须得到列表:

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

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

  • ...

我如何获得这些清单?

1 个答案:

答案 0 :(得分:1)

我建议使用this solution,然后枚举文件夹(针对每个用户)。

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